user3617958 user3617958 - 2 months ago 5x
R Question

Repeat rows based on on a string and replace values of the new rows

I'm having difficulties with this problem.

df <- data.frame(number=1:3,name=c('a','b','c'),code=c("5464","5463,5678","45363,6346,6435"))

If the 3rd column has only 1 set of numbers, don't repeat. For those which have > 1 set of numbers, repeat the row and replace with the subsequent number.

Original output

number name code
1 a "5464"
2 b "5463,5678"
3 c "45363,6346,6435"

Desired output

number name code
1 a "5464"
2 b "5463"
2 b "5678"
3 c "45363"
3 c "6346"
3 c "6435"

I really don't know where to start. I tried using
to separate the strings and count the number of occurrences. But after that I'm having difficulties in repeating the rows based on these occurrences and replacing with the corresponding value.

Any help is appreciated.


We can use separate_rows from tidyr

separate_rows(df, code)

Or cSplit from splitstackshape

cSplit(df, "code", ",", "long")