rdplyrtidyversedata-manipulation

Transforming value into row number


I am conducting some survival analysis and an attempting to turn my wide table into long format for analysis using dplyR. I want to turn the value of 'dead flies' into rows with a binary status for this, for example:

Day Sex Dead(n)
1 Male 1
2 Male 2

into:

Day Sample Sex Status
1 1 Male 1
2 2 Male 1
2 3 Male 1

I've tried some solutions using row_number() but honestly am drawing a blank.

Thank you for any help.


Solution

  • An approach using uncount

    library(dplyr)
    library(tidyr)
    
    df %>% 
      uncount(`Dead(n)`) %>% 
      mutate(Sample=row_number(), Status=1)
      Day  Sex Sample Status
    1   1 Male      1      1
    2   2 Male      2      1
    3   2 Male      3      1