我需要一个专栏与"滞后的差异"之间的具体比较.在数据 struct 中,我有一些大小写重复,我不能只指定LAG=1.我还需要填充了所有大小写并带有不同比较方向(符号)的输出.
看看它的 struct :
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")
)
我需要以下输出:
我能得到的最接近的输出是使用:
df %>%
group_by(id) %>%
mutate(Rk_diff = Rk-Rk[match('A', H_A)]) %>%
ungroup