This question already has an answer here:
- Reshaping multiple sets of measurement columns (wide format) into single columns (long format) 6 answers
I want to gather two seperate groups of columns into two key-value pairs. Here's some example data:
library(dplyr)
library(tidyr)
ID = c(1:5)
measure1 = c(1:5)
measure2 = c(6:10)
letter1 = c("a", "b", "c", "d", "e")
letter2 = c("f", "g", "h", "i", "j")
df = data.frame(ID, measure1, measure2, letter1, letter2)
df = tbl_df(df)
df$letter1 <- as.character(df$letter1)
df$letter2 <- as.character(df$letter2)
I want the values of the two measure columns (measure1 and measure2) to be in one column with a key-column next to it (the key-value pair). I also want the same for letter1 and letter2. I figured that I could use select() to create two different datasets, use gather seperately on both datasets and then join (this worked):
df_measure = df %>%
select(ID, measure1, measure2) %>%
gather(measure_time, measure, -ID) %>%
mutate(id.extra = c(1:10))
df_letter = df %>%
select(ID, letter1, letter2) %>%
gather(letter_time, letter, -ID) %>%
mutate(id.extra = c(1:10))
df_long = df_measure %>%
left_join(df_letter, by = "id.extra")
So this works perfectly (in this case), but i guess this could be done more elegantly (without stuff like splitting or creating 'id.extra').So please shed some light on it!