This question already has an answer here:
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!
We can use
melt
fromdata.table
which can take multiplemeasure
patterns
You can use something like the following. I'm not sure from your current approach if this is exactly your desired output or not since it seems to contain a lot of redundant information.
This is much more easily done with
melt
+patterns
from "data.table":Or you can be old-school and just use
reshape
from base R. Note, however, that base R'sreshape
does not like "tibbles", so you have to convert it withas.data.frame
).