Gather multiple date/value columns using tidyr

前端 未结 5 1004
慢半拍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:21

    The same strategy but using tidyr instead looks as follows:

    df.value <- df %>%
        gather(key="foo", value="value", starts_with("value"))
    df.date <- df %>%
        gather(key="bar", value="date", starts_with("date"))
    

    After controlling the resulting dimensions (careful with NA values - there is also a na.rm argument to the gather function) I joined the data.frames using base/dplyr functions:

    df.long <- data.frame(select(df.value, id, age, value), select(df.date, date))
    

    I am certain there is a much more elgant way to both parts, but it did the trick.

提交回复
热议问题