In R: get multiple rows by splitting a column using tidyr and reshape2

2.2k views Asked by At

What is the most simpel way using tidyr or reshape2 to turn this data:

data <- data.frame(
      A=c(1,2,3),
      B=c("b,g","g","b,g,q"))

Into (e.g. make a row for each comma separated value in variable B):

  A B
1 1 b
2 1 g
3 2 g
4 3 b
5 3 g
6 3 q
1

There are 1 answers

1
akrun On BEST ANSWER

Try

library(splitstackshape)
 cSplit(data, 'B', ',', 'long')

Or using base R

lst <- setNames(strsplit(as.character(data$B), ','), data$A)
stack(lst)

Or

library(tidyr)
 unnest(lst,A)