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
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