My dataset looks something like this:
Id smoke_2m Smoke_3m smoke_4m alcohol_3m age sex
1 2 3 5 7 30 M
2 3 3 5 6 26 M
3 7 5 7 2 25 F
I want my output as follows:
Id Time smoking alcohol age sex
1 2m 2 - 30 M
1 3m 3 7 30 M
1 4m 5 - 30 M
2 2m 3 - 26 M
2 3m 3 6 26 M
2 4m 5 - 26 M
3 2m 7 - 25 F
3 3m 5 2 25 F
3 4m 7 - 25 F
Here for alcohol only 3m values are available so I want the values for other time points (2m,4m) to be empty (-) or filled by the previous value all three alcohol time points would be for eg 7
I tried using this code below however it only performs for one variable i.e smoking
data <- data %>%
pivot_longer(
cols = c(smoke_2m, smoke_3m, smoke_4m),
names_to = "time_point",
values_to = "smoking_status",
)
How to compile for all variables?
The trick here is to use
names_pattern, which allows for its special-case".value"as one ofnames_to.Inferring that you intend for
Smoke_3mto be grouped withinsmoke, though, let's fix that:Data