Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dplyr: how to make copies of rows with one difference based on different columns?

my data currently looks like this:

|Temp | Sex | ID | Survival1 | Surival11 | Survival21 |
|- - -|-----|----|-----------|-----------|------------|
| 30  | Male| 1  |    1      |     1     |     0      |


But I'm trying to make it so that I create 3 rows with Temp/Sex/ID the same but each of the survival columns added on to look like this with a time column

|Temp | Sex | ID | Time | Survival | 
|- - -|-----|----|------|-----------|
| 30  | Male| 1  |  1   |    1      |   
| 30  | Male| 1  |  11  |    1      |
| 30  | Male| 1  |  21  |    0      |

Any help with this would be greatly appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can be done neatly with the tidyr package:

d <- data.frame(Temp = 30, Sex = "Male", ID = 1, Survival1 = 1, Survival11 = 1, Survival21 = 0)

d |>
  tidyr::pivot_longer(Survival1:Survival21,
                      values_to = "Survival", 
                      names_to = "Time",
                      names_pattern = "Survival(.*)")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading