0

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?

Angie
  • 183
  • 3
  • 13

1 Answers1

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