How to pivot multiple times for different variables in one dataframe in R?
Solution 1:
Perhaps this helps
library(tidyr)
pivot_longer(df, cols = matches('^(begin|end)'),
names_to = c("timepoint", ".value"),
names_pattern = "(.*)\\.(\\w+)$", values_drop_na = TRUE)
data
df <- structure(list(childid = c("m1", "m2", "m3", NA, "m4"), begin.age = c(12,
3, NA, 4, 5), end.age = c(14, 5, 6, NA, 7), begin.weight = c(1,
3, NA, 4, 5), end.weight = c(4, 5, 7, NA, 8), phase = c(1, 2,
3, 4, 5)), class = "data.frame", row.names = c(NA, -5L))
Solution 2:
Alternative approach: Similar to akrun's approach but using names_sep
instead of names_pattern
:
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
cols = -c(childid, phase),
names_to = c("timepoint", ".value"),
names_sep = "\\.",
values_drop_na = TRUE
)
childid phase timepoint age weight
<chr> <dbl> <chr> <dbl> <dbl>
1 m1 1 begin 12 1
2 m1 1 end 14 4
3 m2 2 begin 3 3
4 m2 2 end 5 5
5 m3 3 end 6 7
6 m4 4 begin 4 4
7 m5 5 begin 5 5
8 m5 5 end 7 8