1

I am struggling for a few days with a solution myself. Hope you can help. I checked the following already:

I have a dataframe as follows:

df<-list(column=c("apple juice,guava-peach juice,melon apple juice","orange juice,pineapple strawberry lemon juice"))
df<-data.frame(df)

I want to separate each element separated by "," in its own column. Number of columns must be based on the maximum number of elements in each row in column

 column1               column2                              column3
 apple juice       guava-peach juice                  melon apple juice
 orange juice    pineapple strawberry lemon juice             NA

I tried using

library(tidyverse)
library(stringr)

#want to calculate number of columns needed and the sequence 

x<-str_count(df$column)

results<-df%>%separate(column,x,",")

Unfortunately I am not getting what I wish to. Thank you for your help.

Beginner
  • 262
  • 1
  • 4
  • 12

1 Answers1

3

Do you mean this?

library(splitstackshape)
library(dplyr)

df %>%
  cSplit("column", ",")

Output is:

       column_1                         column_2          column_3
1:  apple juice                guava-peach juice melon apple juice
2: orange juice pineapple strawberry lemon juice              <NA>

Sample data:

df <- structure(list(column = structure(1:2, .Label = c("apple juice,guava-peach juice,melon apple juice", 
"orange juice,pineapple strawberry lemon juice"), class = "factor")), .Names = "column", row.names = c(NA, 
-2L), class = "data.frame")
Prem
  • 11,775
  • 1
  • 19
  • 33