-1

I have this dataframe called mydf. What I need to do is replicate the rows for every item separated by comma in the cd column and get the result as shown in result.

mydf<-structure(list(cc = structure(1:3, .Label = c("a", "b", "c"), class = "factor"), 
    cd = structure(1:3, .Label = c("e,f,g", "f,g,s", "g,h,g"), class = "factor"), 
    individuals = structure(1:3, .Label = c("apple", "ball", 
    "cat"), class = "factor")), .Names = c("cc", "cd", "individuals"
), row.names = c(NA, -3L), class = "data.frame")

result

cc   cd          individuals
a    e           apple
a    f           apple 
a    g           apple 
b    f           ball
b    g           ball
b    s           ball
c    g           cat
c    h           cat 
c    g           cat
MAPK
  • 5,635
  • 4
  • 37
  • 88

1 Answers1

1

dplyr way

library(stringi)
library(dplyr)
library(tidyr)

mydf %>%
  mutate(cd = cd %>% stri_split_fixed(",") ) %>%
  unnest(cd)
bramtayl
  • 4,004
  • 2
  • 11
  • 18
  • Please explain how your answer solves the problem, it will help everyone understand your solution with more clarity and for future reference. – Aziz Apr 04 '16 at 02:15