Furmole Furmole - 2 months ago 19
R Question

Split dataframe rows into two copies of itself

I have a data frame where one column has some cells where there are two values. I need to split the two contents of those cells into identical rows except the value at said columns contains one of the two values of that cell.

For example:

X.reagent_short_name X.reagent VIS
buffer Excipient 732323 // 2343434


Would become:

X.reagent_short_name X.reagent VIS
buffer Excipient 732323
buffer Excipient 2343434


Is there a way to do this and maintain the rest of the dataframe?

Answer

With tidyr package, you can use separate_rows():

library(tidyr)
df %>% separate_rows(VIS)

#  X.reagent_short_name X.reagent     VIS
#1               buffer Excipient  732323
#2               buffer Excipient 2343434