For example if I had multiple rows containing a sentence such as "I love dogs" and I wanted to keep the same number of rows in the data frame but have three columns where it would be "I" "love" "dogs" in the respective columns etc. How can I split the one original column at the spaces in the string?
Asked
Active
Viewed 52 times
1 Answers
0
We can use strsplit
and do.call
.
data <- "I love dogs"
do.call(rbind,strsplit(data," "))
# [,1] [,2] [,3]
#[1,] "I" "love" "dogs"
Or for many strings.
data <- data.frame(love = c("I love dogs","I love cats","I love bears","I love dolphins","I love otters"),stringsAsFactors = FALSE)
do.call(rbind,strsplit(data$love," "))
# [,1] [,2] [,3]
#[1,] "I" "love" "dogs"
#[2,] "I" "love" "cats"
#[3,] "I" "love" "bears"
#[4,] "I" "love" "dolphins"
#[5,] "I" "love" "otters"

Ian Campbell
- 23,484
- 14
- 36
- 57
-
can I do this for an entire data frame containing multiple rows with a string in each? – Angie Mar 27 '20 at 02:21
-
Yes. See my edited answer. – Ian Campbell Mar 27 '20 at 02:24