gpt4 book ai didi

r - 过滤后dplyr跨组的行数

转载 作者:行者123 更新时间:2023-12-03 15:45:56 26 4
gpt4 key购买 nike

我想要一个数据帧(过滤后)中每个组的数量和比例(所有元素的比例)。此代码产生所需的输出:

library(dplyr)
df <- data_frame(id = sample(letters[1:3], 100, replace = TRUE),
value = rnorm(100))

summary <- filter(df, value > 0) %>%
group_by(id) %>%
summarize(count = n()) %>%
ungroup() %>%
mutate(proportion = count / sum(count))

> summary
# A tibble: 3 x 3
id count proportion
<chr> <int> <dbl>
1 a 17 0.3695652
2 b 13 0.2826087
3 c 16 0.3478261

是否有一个优雅的解决方案来避免 ungroup()和第二个 summarize()步骤。就像是:
summary <- filter(df, value > 0) %>%
group_by(id) %>%
summarize(count = n(),
proportion = n() / [?TOTAL_ROWS()?])

我在文档中找不到这样的功能,但是我必须缺少明显的东西。谢谢!

最佳答案

您可以在nrow上使用.,它引用管道中输入的整个数据帧:

df %>% 
filter(value > 0) %>%
group_by(id) %>%
summarise(count = n(), proportion = count / nrow(.))

# A tibble: 3 x 3
# id count proportion
# <chr> <int> <dbl>
#1 a 14 0.2592593
#2 b 22 0.4074074
#3 c 18 0.3333333

关于r - 过滤后dplyr跨组的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47514108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com