0

Suppose you have a dataframe with an Id x and a string y :

x  y
1  a-b-c
2  d-e

I want the following dataframe :

x  y
1  a
1  b
1  c
2  d
2  e
Rodolphe LAMPE
  • 1,346
  • 2
  • 11
  • 17
  • 1
    http://stackoverflow.com/questions/13773770/split-comma-separated-column-into-separate-rows – rawr Jan 14 '17 at 16:22

2 Answers2

3

Try using separate_rows from tidyr:

library(tidyr)


dff <- structure(list(x = 1:2, 
               y = structure(1:2, .Label = c("a-b-c","d-e"), 
              class = "factor")), .Names = c("x", "y"), 
              class = "data.frame", row.names = c(NA,-2L))

dff %>%
    separate_rows(y)

#  x y
#1 1 a
#2 1 b
#3 1 c
#4 2 d
#5 2 e

I hope it helps.

Abdou
  • 12,931
  • 4
  • 39
  • 42
2

We can try

library(splitstackshape)
cSplit(dff, "y", "-", "long")
#   x y
#1: 1 a
#2: 1 b
#3: 1 c
#4: 2 d
#5: 2 e
akrun
  • 874,273
  • 37
  • 540
  • 662