1

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!

Cold2Breath
  • 111
  • 6

1 Answers1

1

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  
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    Okay, now I feel quite stupid, I anticipated that this would require a complicated if loop to iterate over each row, split the cell, copy the other values and paste them etc. Did not knew about this function until now, thank you very much! :) – Cold2Breath Aug 12 '21 at 23:44