如何根据过滤条件添加计数列而不是在dplyr中进行分组?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何根据过滤条件添加计数列而不是在dplyr中进行分组?相关的知识,希望对你有一定的参考价值。
以下是我的资产数据的子集
# df1 <- AllAssets %>%
# filter(country %in% c('Morocco', 'Gabon', 'Tunisia')) %>%
# group_by(country, named, active) %>%
# summarize(assets = n())
相当于此数据框:
library(dplyr)
library(tibble)
df1 <- structure(list(country = c("Gabon", "Gabon", "Gabon", "Morocco",
"Morocco", "Tunisia", "Tunisia", "Tunisia"), named = c(FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE), active = c(1, 0,
1, 0, 1, 0, 0, 1), assets = c(8L, 305L, 271L, 254L, 18L, 24L,
350L, 282L)), class = "data.frame", row.names = c(NA, -8L), .Names = c("country",
"named", "active", "assets")) %>% as.tibble() %>% group_by(country, named)
# A tibble: 8 x 4
# Groups: country, named [5]
# country named active assets
# <chr> <lgl> <dbl> <int>
# 1 Gabon FALSE 1. 8
# 2 Gabon TRUE 0. 305
# 3 Gabon TRUE 1. 271
# 4 Morocco TRUE 0. 254
# 5 Morocco TRUE 1. 18
# 6 Tunisia FALSE 0. 24
# 7 Tunisia TRUE 0. 350
# 8 Tunisia TRUE 1. 282
我正在制作一个电子表格,根据不同的变量条件计算一个国家的资产数量。有没有比我在下面写的更简单,更清晰的方式来获得我的输出?
df1 %>%
mutate(ctry_namedTF_count = sum(assets)) %>%
group_by(country) %>%
mutate(ctry_count = sum(assets)) %>%
filter(named == TRUE, active == 1) %>%
select(-(named:active)) %>%
rename(named_active = assets,
TotalAssets = ctry_count,
named = ctry_namedTF_count)
# Output:
# A tibble: 3 x 4
# Groups: country [3]
country named_active named TotalAssets
<chr> <int> <int> <int>
1 Gabon 271 576 584
2 Morocco 18 272 272
3 Tunisia 282 632 656
我实际上是按照dplyr vignette(Ctrl-F'汇总')中的描述“卷起”我的数据帧,重复调用sum(),并重复添加一个数字,而不仅仅是计算分组情况。但是我所拥有的功能虽然很难阅读,但我想知道是否有更简单的方法或自定义功能更有意义。
例如,dplyr :: add_count非常简单,可用于添加一个列,用于计算一个或多个列中的组案例,
> df1 %>% add_count(country, named)
# A tibble: 8 x 5
# Groups: country, named [5]
country named active assets n
<chr> <lgl> <dbl> <int> <int>
1 Gabon FALSE 1. 8 1
2 Gabon TRUE 0. 305 2
3 Gabon TRUE 1. 271 2
4 Morocco TRUE 0. 254 2
5 Morocco TRUE 1. 18 2
6 Tunisia FALSE 0. 24 1
7 Tunisia TRUE 0. 350 2
8 Tunisia TRUE 1. 282 2
而且我想知道是否有一些东西可以在这些分组之间加总变量。
这样的功能是否存在于基本R或其他重大包中?像df1 %>% add_aggregate_by_vars_filters(vars = named, filter = 'named == TRUE', sum_var = assets)
,或类似的清洁和实用的东西?
答案
library(dplyr)
df1 <- structure(list(country = c("Gabon", "Gabon", "Gabon", "Morocco",
"Morocco", "Tunisia", "Tunisia", "Tunisia"), named = c(FALSE,
TRUE, TRUE, TRUE, TRUE, FALSE, TRUE, TRUE), active = c(1, 0,
1, 0, 1, 0, 0, 1), assets = c(8L, 305L, 271L, 254L, 18L, 24L,
350L, 282L)), class = "data.frame", row.names = c(NA, -8L), .Names = c("country",
"named", "active", "assets"))
df1 %>%
group_by(country) %>%
summarise(named_active = sum(assets[named==TRUE & active==1]),
named = sum(assets[named==TRUE]),
TotalAssets = sum(assets[active==1]))
# # A tibble: 3 x 4
# country named_active named TotalAssets
# <chr> <int> <int> <int>
# 1 Gabon 271 576 279
# 2 Morocco 18 272 18
# 3 Tunisia 282 632 282
以上是关于如何根据过滤条件添加计数列而不是在dplyr中进行分组?的主要内容,如果未能解决你的问题,请参考以下文章