I am in need of a column with "lagged differences" between specific comparison. In the data structure I have some case repetitions and I can't just assign lag =1. I also need the output with all cases filled and with the distinct direction (sign) of the comparison.
Take a look at the structure:
df <- structure(
list(
id = c(1, 1, 2, 2, 3, 3, 3, 4, 4, 4),
H_A = c("H",
"A", "H", "A", "H", "H", "A", "H", "A", "A"),
Rk = c(6, 15, 19,
7, 8, 8, 10, 12, 3, 3)
),
row.names = c(NA,-10L),
class = c("tbl_df",
"tbl", "data.frame")
)
I need this output:
The closest output I could get was using:
df %>%
group_by(id) %>%
mutate(Rk_diff = Rk-Rk[match('A', H_A)]) %>%
ungroup
