3

I'm working with a string that is a list of elements separated by commas. I want to separate the string so that each element has its column. But I'm having trouble because there are a different number of elements per list.

X1 <- "a,b,c"
X2 <- "a,b"
X3 <- "a,b,c,d"

DF <- data.frame(Col1= rbind(X1,X2,X3))

      Col1
X1   a,b,c
X2     a,b
X3 a,b,c,d

I would like it to look like this. Where each element has its own column, irrespective of how many elements there are in the character's string.

      Col1  Col2 Col3 Col4
X1     a    b     c
X2     a    b
X3     a    b     c    d

Thank You!

Sharif Amlani
  • 1,138
  • 1
  • 11
  • 25

3 Answers3

4

We could use cSplit from splitstackshape

library(splitstackshape)
cSplit(DF, "Col1",",")

-output

cSplit(DF, "Col1",",")
   Col1_1 Col1_2 Col1_3 Col1_4
1:      a      b      c   <NA>
2:      a      b   <NA>   <NA>
3:      a      b      c      d
akrun
  • 874,273
  • 37
  • 540
  • 662
3

Alternative solution using stringr:

X1 <- "a,b,c"
X2 <- "a,b"
X3 <- "a,b,c,d"

DF <- data.frame(Col1= rbind(X1,X2,X3))

require(stringr)
data.frame(str_split(DF$Col1, ",", simplify=TRUE))

Output

  X1 X2 X3 X4
1  a  b  c   
2  a  b      
3  a  b  c  d
J M
  • 122
  • 6
1

Another way: We could be:

library(tidyverse)

as_tibble(DF) %>% separate(Col1, into = paste("Col", 1:4, sep = "_"))
  Col_1 Col_2 Col_3 Col_4
  <chr> <chr> <chr> <chr>
1 a     b     c     NA   
2 a     b     NA    NA   
3 a     b     c     d    
TarJae
  • 72,363
  • 6
  • 19
  • 66