Is there a R function to split cell into new rows (while duplicating data)?

Viewed 46

I have a dataframe like this:

Sent_From <- c("1","2","3","4")
Timestamp <- c("01:00","02:00","03:00","04:00")
Send_To <- c("id1", "id2,id3", "id4", "id5,id1,id2,id4")
mydf <- data.frame(Sent_From, Timestamp, Send_To)

I would like to create a new row for each observation in column "Send_to" in order to end up with something like this:

Sent_From <- c("1","2","2","3","4","4","4","4")
Timestamp <- c("01:00","02:00","02:00","03:00","04:00","04:00","04:00","04:00")
Send_To <- c("id1", "id2","id3", "id4", "id5","id1","id2","id4")
mydf_spreaded <- data.frame(Sent_From, Timestamp, Send_To)

How would I start addressing a problem like this? I imaging splitting each cell in column "Send_to" by each "," but I don't now how to create a new row for each splitted cell with the same data. Basically I am searching for a solution like here, but in R!

1 Answers

We can use separate_rows

library(dplyr)
library(tidyr)
mydf %>%
     separate_rows(Send_To)

-ouput

# A tibble: 8 x 3
  Sent_From Timestamp Send_To
  <chr>     <chr>     <chr>  
1 1         01:00     id1    
2 2         02:00     id2    
3 2         02:00     id3    
4 3         03:00     id4    
5 4         04:00     id5    
6 4         04:00     id1    
7 4         04:00     id2    
8 4         04:00     id4  
Related