R: how to display the first n characters from a string of words

[亡魂溺海] 提交于 2019-12-05 05:40:16

The other answers didn't eliminate the spaces as you did in your example, so I'll add this:

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

Turn your code around and you get what you want.

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"

The reason why you got "c(\"F\", \"o\"" is because the strsplit output is a list. We can convert the list to vector by extracting the first list element ie. [[1]]. Use the head to get the first 10 characters.

head(strsplit(Getty, '')[[1]], 10)

Update

If you just want to extract characters without the spaces,

library(stringr)
head(str_extract_all(Getty, '[^ ]')[[1]],10)
#[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!