R:如何从一串单词中显示前n个字符

map*_*eaf 7 string r substr strsplit

我有以下字符串:

 Getty <- "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all  men are created equal."
Run Code Online (Sandbox Code Playgroud)

我想显示前10个字符.所以我开始将字符串拆分为单个字符:

 split <- strsplit(Getty, split="")
 split 
Run Code Online (Sandbox Code Playgroud)

我得到了所有个人角色.然后我创建前10个字符的子字符串.

 first.10 <- substr(split, start=1, stop=10)
 first.10
Run Code Online (Sandbox Code Playgroud)

这是输出:

 "c(\"F\", \"o\""
Run Code Online (Sandbox Code Playgroud)

我不明白为什么打印出来?我以为它会打印出如下内容:

 "F" "o" "u" "r" "s" 
Run Code Online (Sandbox Code Playgroud)

有没有办法可以改变我的代码来打印上面的内容?

谢谢大家!

phi*_*ver 5

扭转你的代码,你就会得到你想要的。

Getty <- "Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all  men are created equal."


first.10 <- substr(Getty, start=1, stop=10)
first.10
"Four score"
split <- strsplit(first.10, split="")
split 
"F" "o" "u" "r" " " "s" "c" "o" "r" "e"
Run Code Online (Sandbox Code Playgroud)


Pie*_*une 4

其他答案没有像您在示例中那样消除空格,所以我将添加以下内容:

strsplit(substr(gsub("\\s+", "", Getty), 1, 10), '')[[1]]
#[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a"
Run Code Online (Sandbox Code Playgroud)