In my dataset, I have individuals with sometimes 2 time points, and I would like to set the difference between the 2 time points. The thing is that I have a lot of columns that I would like to apply this to. In my dataset, I have either 1 or 2 rows per individual; here is an example of what I have done with 2 columns:
library(tidyr)
data = data.frame(id = c(1,1,2,2,3,4,5,5,6),
time = c("M0","M3","M0","M3","M0","M0","M0","M3","M0"),
bio1 = c(4.2, 4.8, 4, NA, 3.8, 4.4, 5, 6, 6.1),
bio2 = c(12, 14, 10, 11, NA, 18, 19, 12, 15))
data
data_wide <- data %>%
pivot_wider(names_from="time",
values_from=c("bio1","bio2")) %>%
mutate(diff_bio1 = bio1_M3 - bio1_M0,
diff_bio2 = bio2_M3 - bio2_M0) %>%
select(id, diff_bio1, diff_bio2)
data_wide
I know with pivot_wider we can aggregate functions on every separated column we create, but I didn't find a way to apply the function directly at the creation to set the difference. Is there a way to do that ?