Why strsplit returns a list

Consider

text <- "who let the dogs out" fooo <- strsplit(text, " ") fooo [[1]] [1] "who" "let" "the" "dogs" "out" 

strsplit output is a list. The first element of the list is a vector containing the words above.

Why does a function behave like this? Is there any case where it will return a list with more than one item?

And I can access the words using

 fooo[[1]][1] [1] "who" 

but is there an easier way?

+5
source share
1 answer

To your first question, one of the reasons that comes to mind is that it can store result vectors of different lengths in the same object, since it is vectorized over x :

 text <- "who let the dogs out" vtext <- c(text, "who let the") ## > strsplit(text, " ") [[1]] [1] "who" "let" "the" "dogs" "out" > strsplit(vtext, " ") [[1]] [1] "who" "let" "the" "dogs" "out" [[2]] [1] "who" "let" "the" 

If it were to be returned as data.frame , matrix , etc. instead of list , it should be supplemented with additional elements.

+9
source

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


All Articles