Gather multiple date/value columns using tidyr

前端 未结 5 1002
慢半拍i
慢半拍i 2020-12-19 17:14

I have a data set containing (amongst others) multiple columns with dates and corresponding values (repeated measurements). Is there a way to turn this into a long data set

5条回答
  •  天命终不由人
    2020-12-19 17:39

    I stumbled across this trying to learn about using gather with a mix of dates and values.

    The existing answers lose information about which instance the date-value pair came from, ie, instance 1 for date1 & value1, etc. This may not be important, but here's a tidyverse option that keeps the instance.

    library(stringr) # not necessary but nice
    library(tidyr)
    library(dplyr)
    
    df %>% 
        gather(key, val, -id, -age) %>% 
        mutate(
            measure = str_sub(key,1,-2), 
            instance = str_sub(key, -1)
        ) %>% 
        select(-key) %>% 
        spread(measure, val) %>% 
        mutate(date = as.Date(date, origin="1970-01-01")) # restore date class
    

提交回复
热议问题