Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split column by deliminter '+' with R

Tags:

r

For example I got :

V1 <- c("apple + orange + banana","apple+green + orange + banana")
#careful, there is no space in "apple+green"
data <- data.frame(V1) 
                             V1
1       apple + orange + banana
2 apple+green + orange + banana

And I would like this kind of dataframe :

data_final 

              V1     V2       V3
    1       apple  orange  banana
    2 apple+green  orange  banana

I tried with strsplit :

strsplit(as.character(data$V1), ' +', fixed=TRUE)

I added a space because of the string "apple+green". But the result gave me a column composed by a list. And I want a dataframe

Could you please help me?

like image 919
Antoine F Avatar asked Dec 23 '22 06:12

Antoine F


1 Answers

You can also try this with splitstackshape package:

library(splitstackshape)
x <- cSplit(data, 'V1', ' + ')

Result:

          V1_1   V1_2   V1_3
1:       apple orange banana
2: apple+green orange banana
like image 146
Ankur Sinha Avatar answered Jan 03 '23 01:01

Ankur Sinha