繁体   English   中英

如何使用 R dplyr's summarize 来计算符合条件的行数?

[英]How to use R dplyr's summarize to count the number of rows that match a criteria?

我有一个要总结的数据集。 首先,我想要主场和客场比赛的总和,我可以做到。 但是,我还想知道每个子类别(主场、客场)中有多少异常值(定义为超过 300 分)。

如果我没有使用 summarize,我知道dplyrcount() function,但我希望这个解决方案出现在我的summarize()调用中。 这是我所拥有的和我尝试过的,但未能执行:

#Test data
library(dplyr)

test <- tibble(score = c(100, 150, 200, 301, 150, 345, 102, 131),
                  location = c("home", "away", "home", "away", "home", "away", "home", "away"),
                  more_than_300 = c(FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, FALSE, FALSE))


#attempt 1, count rows that match a criteria
test %>%
  group_by(location) %>%
  summarize(total_score = sum(score),
            n_outliers = nrow(.[more_than_300 == FALSE]))

您可以对逻辑向量使用sum - 它会自动将它们转换为数值( TRUE等于 1, FALSE等于 0),因此您只需执行以下操作:

test %>%
  group_by(location) %>%
  summarize(total_score = sum(score),
            n_outliers  = sum(more_than_300))
#> # A tibble: 2 x 3
#>   location total_score n_outliers
#>   <chr>          <dbl>      <int>
#> 1 away             927          2
#> 2 home             552          0

或者,如果这些是您仅有的 3 列,则等效项是:

test %>%
  group_by(location) %>%
  summarize(across(everything(), sum))

事实上,您不需要制作more_than_300列 - 这样做就足够了:

test %>%
  group_by(location) %>%
  summarize(total_score = sum(score),
            n_outliers  = sum(score > 300))

在 base R 中,我们可以像这样尝试aggregate

> aggregate(.~location,test,sum)
  location score more_than_300
1     away   927             2
2     home   552             0

在基础xtabs中可以用来总结每组。

xtabs(cbind(score, more_than_300) ~ ., test)
#location score more_than_300
#    away   927             2
#    home   552             0

或者通过动态计算异常值并给出所需的列名。

xtabs(cbind(total_score = score, n_outliers = score > 300) ~ location, test)
#location total_score n_outliers
#    away         927          2
#    home         552          0

另一个选项,也是在 base 中,将是rowsum

with(test, rowsum(cbind(total_score = score, n_outliers = score > 300), location))
#     total_score n_outliers
#away         927          2
#home         552          0

xtabsrowsum专门用于计算每组的总和,并且可能在此任务中表现出色。

暂无
暂无

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

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