数据样本的结构如下:
Individ <- data.frame(Participant = c("Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill", "Bill",
"Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry", "Harry"),
Time = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12),
Power = c(400, 250, 180, 500, 300, 450, 600, 512, 300, 500, 450, 200, 402, 210, 130, 520, 310, 451, 608, 582, 390, 570, NA, NA))
我在两秒,三秒和四秒钟内计算Power
的滚动平均值。我知道我可以通过执行以下操作来对每个滚动平均值进行子集化(考虑Participant
中的更改):
Individ$TwoSec <- ave(Individ$Power, Individ$Participant,
FUN= function(x) rollapply(x, 2, mean, na.rm = TRUE, fill = NA) )
Individ$ThreeSec <- ave(Individ$Power, Individ$Participant,
FUN= function(x) rollapply(x, 3, mean, na.rm = TRUE, fill = NA) )
Individ$FourSec <- ave(Individ$Power, Individ$Participant,
FUN= function(x) rollapply(x, 4, mean, na.rm = TRUE, fill = NA) )
我现在希望找到每个滚动平均值Power
,TwoSec
和ThreeSec
的{{1}}的前5%。如何解决FourSec
中的更改并计算此内容?
我的实际Name
是&gt; 300万行,因此首选快速解决方案。
答案 0 :(得分:3)
我们可以试试
library(data.table)
library(RcppRoll)
setDT(Individ)[, lapply(2:4, function(n) {
r1 <- roll_mean(Power, n, fill=NA)
r2 <- r1[order(-r1)]
r2[seq(ceiling(.N*0.05))]}) , by = Participant]