我想根据日期计算每个人的第一个得分和最后一个得分之间的差值。原始数据如下所示:
ID <- c(1,1,1,2,2,3,3,3,3,4)
Score <- c(3,2,1,1,2,0,0,3,4,0)
Date <- c("2020/01/01","2020/01/02","2020/01/03","2020/02/05","2020/02/06","2021/10/01","2021/10/02","2021/10/03","2021/10/04","2022/03/01")
a <- data.frame(ID,Score,Date)
所需数据集:
diff_first_last <- c(-2,-2,-2,1,1,4,4,4,4,0)
b <- data.frame(ID,Score,Date,diff_first_last)
有没有一种方法可以很容易地做到这一点,因为我想把它应用到一个更大的数据集。我会感谢所有的帮助有!谢谢!!!
2条答案
按热度按时间yebdmbv41#
在 base 中,可以使用
ave
,假设它是按日期排序的。以防它没有排序。
基准
在这种情况下,base 解决方案比DPH2快大约4倍,但使用的内存是DPH2的两倍。
zpf6vheq2#
这是一种可能的DPLYR解决方案:
编辑:正如@GKi指出的代码很慢-关键的优化是将lubridate::ymd()更改为as.Date()...通过改变组大小但保持唯一观察的数量或多或少相同来测试更大的数据集,我们观察到以下性能(dplyr解决方案在大组上表现更好):