You can either reshape the data wider and then compute the difference between two variables as normal, or you can keep the data in long format and extract a specific element from each vector (broken down by group) as suggested by TarJae.
Reshaping wider (as shown below) has the advantage that it does not require a
and b
to be in the correct order.
library(tidyverse)
df |>
pivot_wider(
names_from = timepoint,
values_from = value
) |>
mutate(difference = b - a)
#> # A tibble: 5 × 6
#> subject var session a b difference
#> <int> <chr> <chr> <int> <int> <int>
#> 1 1 SMSPAg T1 50 48 -2
#> 2 1 SMSPAg T2 52 65 13
#> 3 1 SMSPAg T3 51 61 10
#> 4 2 SMSPAg T1 53 50 -3
#> 5 2 SMSPAg T2 54 NA NA
Created on 2023-04-13 with reprex v2.0.2
where
df <- tribble(
~subject, ~var, ~session, ~timepoint, ~value,
1L, "SMSPAg", "T1", "a", 50L,
1L, "SMSPAg", "T1", "b", 48L,
1L, "SMSPAg", "T2", "a", 52L,
1L, "SMSPAg", "T2", "b", 65L,
1L, "SMSPAg", "T3", "a", 51L,
1L, "SMSPAg", "T3", "b", 61L,
2L, "SMSPAg", "T1", "a", 53L,
2L, "SMSPAg", "T1", "b", 50L,
2L, "SMSPAg", "T2", "a", 54L
)