Search code examples
rdatedplyrdata.tableextract

R: generate value rows for each date extracted


I have a dataframe like this:

ID   Year   Week  Monday  Tuesday  Wednesday
12   2017    42     8         9         8,5
12   2017    43     9         11        7,3
13   2017    43     9         10        6,8

I would like to change it in order to achive this:

ID   day          time
12   16/10/2017   8
12   17/10/2017   9
12   18/10/2017   8,5
12   23/10/2017   9
12   24/10/2017   11
12   25/10/2017   7,3
12   23/10/2017   9
12   24/10/2017   10
12   25/10/2017   6,8

I´m trying by using dplyr but still I have not found a solution


Solution

  • library(dplyr)
    library(tidyr)
    
    df %>% 
      gather(day, time, Monday:Wednesday) %>%
      mutate(date = as.Date(paste(Year, Week, day),"%Y %U %A")) %>%
      arrange(ID, Year, Week) %>%
      select(-Year, -Week, -day)
    
    #  ID time       date
    #1 12    8 2017-10-16
    #2 12    9 2017-10-17
    #3 12  8,5 2017-10-18
    #4 12    9 2017-10-23
    #5 12   11 2017-10-24
    #6 12  7,3 2017-10-25
    #7 13    9 2017-10-23
    #8 13   10 2017-10-24
    #9 13  6,8 2017-10-25
    

    #sample data
    > dput(df)
    structure(list(ID = c(12L, 12L, 13L), Year = c(2017L, 2017L, 
    2017L), Week = c(42L, 43L, 43L), Monday = c(8L, 9L, 9L), Tuesday = c(9L, 
    11L, 10L), Wednesday = structure(c(3L, 2L, 1L), .Label = c("6,8", 
    "7,3", "8,5"), class = "factor")), .Names = c("ID", "Year", "Week", 
    "Monday", "Tuesday", "Wednesday"), class = "data.frame", row.names = c(NA, 
    -3L))