繁体   English   中英

如何有效地计算总和和相对计数频率?

[英]How to efficiently calculate the sum and relative count frequency?

我正在寻找一种单行 dplyr 解决方案,用于在分数上过滤 data.frame,然后计算相对计数频率。

经典的 R 解决方案如下:

daf <- data.frame(score=c(1:40),count=sample(1:1000,40,replace=T))
select <- daf$score >= 30
res <- c(sum(daf$count[select]),sum(daf$count[select])/sum(daf$count))

我的第一个 dplyr 解决方案重复了结果:

daf %>% 
  mutate(total=sum(count)) %>% 
  filter(score >= 30) %>% 
  summarise(
    sum_count=sum(count),
    sum_rel=sum(count)/total
  )

dplyr 代码有什么更好的想法吗?

假设total列总是相同的值,使用max(total)而不是totalsummarise

daf %>% 
  mutate(total = sum(count)) %>%
  filter(score >= 30) %>%
  summarise(sum_count = sum(count),
            sum_rel = sum(count) / max(total))

  sum_count   sum_rel
1      5535 0.2621608

编辑:根据@GregorThomas 的评论,对于大型数据集,使用first()而不是max()会更有效。

daf %>% 
  mutate(total = sum(count)) %>%
  filter(score >= 30) %>%
  summarise(sum_count = sum(count),
            sum_rel = sum(count) / first(total))
library(dplyr)
daf %>%
  summarize(
    sum_count = sum(count[score >= 30]), 
    sum_rel = sum_count / sum(count)
  )
#   sum_count  sum_rel
# 1      5661 0.301053

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM