Almost every data tidying problem can be solved in three steps:
- Gather all non-variable columns
- Separate "colname" column into multiple variables
- Re-spread the data
(often you'll only need one or two of these, but I think they're almost always in this order).
For your data:
- The only column that's already a variable is
unique.id
- You need to split current column names into variable and number
- Then you need to put the "variable" variable back into columns
This looks like:
library(tidyr)
library(dplyr)
df3 %>%
gather(col, value, -unique.id, -intervention) %>%
separate(col, c("variable", "number")) %>%
spread(variable, value, convert = TRUE) %>%
mutate(start = as.Date(start, "1970-01-01"), stop = as.Date(stop, "1970-01-01"))
Your case is a bit more complicated because you have two types of variables, so you need to restore the types at the end.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…