提问人:cliu 提问时间:6/28/2023 最后编辑:cliu 更新时间:6/28/2023 访问量:36
如果一列中的值匹配,则计算差值
Calculate the difference if the values in one column match
问:
我有一些纵向数据,其中某些人的倒置在某些时间点丢失:
df <- data.frame(id = c(1, 1, 1, 1, 1, 2, 2, 2), #id2 is missing for time 3 and 5
time = c(1, 2, 3, 4, 5, 1, 2, 4),
value = c(3, 4, 2, 55, 5, 9, 43, 22))
如果两个人共享相同的时间点,我想计算他们之间的差异,否则我们用 .预期成果如下:NA
id time value diff
1 1 3 -6 #the time point matches and so calculate the difference
1 2 46 3
1 3 2 NA
1 4 55 33
1 5 5 NA
2 1 9 -6
2 2 43 3
2 3 NA NA
2 4 22 33
2 5 NA NA
如何快速实现这一目标?我有一个更大的数据集。
答:
2赞
Axeman
6/28/2023
#1
用:dplyr
df %>%
arrange(id) %>% # make sure id 1 comes first
group_by(time) %>%
mutate(diff = ifelse(n() == 2, -diff(value), NA)) %>%
ungroup()
给:
# A tibble: 8 × 4 id time value diff <dbl> <dbl> <dbl> <dbl> 1 1 1 3 -6 2 1 2 4 -39 3 1 3 2 NA 4 1 4 55 33 5 1 5 5 NA 6 2 1 9 -6 7 2 2 43 -39 8 2 4 22 33
评论
1赞
cliu
6/28/2023
没错。我更正了.谢谢@Axemandf
1赞
Axeman
6/28/2023
如果需要表中的所有内容(如预期输出),请添加(可能很慢)。id == 2
%>% complete(id, time)
评论