我有一个这样的data.frame
dat <- data.frame(id = rep(1:4, each = 4),
x = 1:16,
y = 16:1)
library(dplyr)
我想对每个对象执行以下操作 id
for id 1, do mean(x)/mean(y),
for id 2, do mean(x)/mean(y) where x and y includes values from id 1 and 2
for id 3, do mean(x)/mean(y) where x and y includes values from id 1, 2 and 3
for id 4, do mean(x)/mean(y) where x and y includes values from id 1, 2, 3 and 4
我做了一个传统的for循环来做到这一点
temp.vec <- list()
for(l in sort(unique(dat$id))){
temp.vec[[l]] <- dat %>%
dplyr::filter(id <= l) %>%
dplyr::summarise(value = mean(x)/mean(y))
print(l)
}
result <- rbindlist(temp.vec)
result
value
1: 0.1724138
2: 0.3600000
3: 0.6190476
4: 1.0000000
我可以使用dplyr吗?
dat %>%
group_by(id) %>%
summarise(mean_x = mean(x), mean_y = mean(y)) %>%
mutate(result = cumsum(mean_x) / cumsum(mean_y)) %>%
pluck("result")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句