If you're curious what an approach looks like using gather():
Note:
- Thank you @vlad_aluas for the data.
-
key and value are the names of the new columns.
-
1:4 indicate the selection of columns that are to be gathered into key-value pairs (from wide to long).
-
arrange is used to match the pivot_longer solution provided by @vlad_aluas.
library(dplyr)
library(tidyr)
df <- tibble(
ID = c("A", "B", "C"),
var1 = c(10, 9, 8),
var2 = c("blue", "green", "pink"),
`t0` = c(0, 0, 0),
`t1` = c(1, 1, 1),
`t2` = c(2, 2, 2),
`t100` = c(100, 100, 100)
)
df %>%
gather(key = 'measurement_time',
value = 'measurement_value',
4:7) %>%
arrange(ID)
Output
#> # A tibble: 12 x 5
#> ID var1 var2 measurement_time measurement_value
#> <chr> <dbl> <chr> <chr> <dbl>
#> 1 A 10 blue t0 0
#> 2 A 10 blue t1 1
#> 3 A 10 blue t2 2
#> 4 A 10 blue t100 100
#> 5 B 9 green t0 0
#> 6 B 9 green t1 1
#> 7 B 9 green t2 2
#> 8 B 9 green t100 100
#> 9 C 8 pink t0 0
#> 10 C 8 pink t1 1
#> 11 C 8 pink t2 2
#> 12 C 8 pink t100 100
Created on 2021-03-19 by the reprex package (v0.3.0)