我有一个如下所示的数据集(dat):
Team Person Performance1 Performance2
1 36465930 1 101
1 37236856 1 101
1 34940210 1 101
1 29135524 1 101
2 10318268 1 541
2 641793 1 541
2 32352593 1 541
2 2139024 1 541
3 35193922 2 790
3 32645504 2 890
3 32304024 2 790
3 22696491 2 790
我正在尝试识别并删除所有在Performance1或Performance2上存在差异的团队。因此,例如,示例中的团队3在性能2上存在差异,因此我希望从数据集中删除该团队。这是我写的代码:
tda <- aggregate(dat, by=list(data$Team), FUN=sd)
tda1 <- tda[ which(tda$Performance1 != 0 | tda$Performance2 != 0), ]
问题是我的数据集中有超过100,000个团队,所以我的第一行代码花了很长时间,而且我不确定它是否会完成聚合数据集。什么是解决这个问题的更有效方法?
提前致谢! :)
此致 艾米
答案 0 :(得分:2)
dplyr
包通常非常快。这是一种仅选择Performance1
和Performance2
标准偏差等于零的团队的方式:
library(dplyr)
datAggregated = dat %>%
group_by(Team) %>%
summarise(sdP1 = sd(Performance1),
sdP2 = sd(Performance2)) %>%
filter(sdP1==0 & sdP2==0)
datAggregated
Team sdP1 sdP2
1 1 0 0
2 2 0 0
答案 1 :(得分:0)
将data.table
用于大数据集
library(data.table)
setDT(dat)[, setNames(lapply(.SD,sd), paste0("sdP", 1:2)),
.SDcols=3:4, by=Team][,.SD[!sdP1& !sdP2]]
# Team sdP1 sdP2
#1: 1 0 0
#2: 2 0 0
如果您有更多Performance
列,则可以使用summarise_each
中的dplyr
datNew <- dat %>%
group_by(Team) %>%
summarise_each(funs(sd), starts_with("Performance"))
colnames(datNew)[-1] <- paste0("sdP", head(seq_along(datNew),-1))
datNew[!rowSums(datNew[-1]),]
给出输出
# Team sdP1 sdP2
#1 1 0 0
#2 2 0 0