Harvey Harvey - 2 months ago 8
R Question

R - How to split one column with comma to multiple columns

My original table looks like below:

A B
1 a,b
2 c,d,e
3 f


I want to get result as below:

A B
1 a
1 b
2 c
2 d
2 e
3 f


How can I use R to do this?

Answer

We can use cSplit

library(splitstackshape)
cSplit(df1, "B", ",", "long")
#   A B
#1: 1 a
#2: 1 b
#3: 2 c
#4: 2 d
#5: 2 e
#6: 3 f