简体   繁体   中英

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

I have the following string:

 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."

I want to display the first 10 characters. So I began by splitting the string into individual characters:

 split <- strsplit(Getty, split="")
 split 

I get all the individual characters as this point. Then I make a substring of the first 10 characters.

 first.10 <- substr(split, start=1, stop=10)
 first.10

And here is the output:

 "c(\"F\", \"o\""

I am not understanding why this prints out? I thought it would just print out something like:

 "F" "o" "u" "r" "s" 

Is there a way I can alter my code to print what I have above?

Thank you everyone!

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 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"

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM