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

I have the following line:

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 started by breaking the string into separate characters:

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

I get all individual characters like this item. Then I create a substring of the first 10 characters.

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

And here is the conclusion:

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

I do not understand why this is printing? I thought it would just print something like:

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

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

Thanks everyone!

+5
source share
3 answers

Other answers did not eliminate the spaces, as in your example, so I will add the following:

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

Turn your code 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" 
+3
source

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

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

Update

If you just want to extract characters without spaces,

 library(stringr) head(str_extract_all(Getty, '[^ ]')[[1]],10) #[1] "F" "o" "u" "r" "s" "c" "o" "r" "e" "a" 
+2
source

Source: https://habr.com/ru/post/1233969/


All Articles