你可以使用下面的基本语法在R中进行group by和count with condition:
library(dplyr)
df %>%
group_by(var1) %>%
summarize(count = sum(var2 == 'val'))
这个特殊的语法是根据var1对数据框的行进行分组,然后对var2等于'val'的行数进行计数。
下面的例子展示了如何在实践中使用这种语法。
例子:R中的Group By和Count with Condition
假设我们在R中拥有以下数据框,其中包含各种篮球运动员的信息:
#create data frame
df <- data.frame(team=c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'),
pos=c('Gu', 'Fo', 'Fo', 'Fo', 'Gu', 'Gu', 'Fo', 'Fo'),
points=c(18, 22, 19, 14, 14, 11, 20, 28))
#view data frame
df
team pos points
1 A Gu 18
2 A Fo 22
3 A Fo 19
4 A Fo 14
5 B Gu 14
6 B Gu 11
7 B Fo 20
8 B Fo 28
下面的代码显示了如何通过球队变量对数据框进行分组,并计算pos变量等于'gu'的行数:
library(dplyr)
#group by team and count rows where pos is 'Gu'
df %>%
group_by(team) %>%
summarize(count = sum(pos == 'Gu'))
# A tibble: 2 x 2
team count
1 A 1
2 B 2
从输出中我们可以看到:
- 球队A有1行的位置列等于 "Gu"。
- 团队B有2行,其中pos列等于'Gu'。
我们可以使用类似的语法来执行group by和带有一些数字条件的计数。
例如,下面的代码显示了如何通过团队变量分组并计算积分 变量大于15的行数:
library(dplyr)
#group by team and count rows where pos is 'Gu'
df %>%
group_by(team) %>%
summarize(count = sum(points > 15))
# A tibble: 2 x 2
team count
1 A 3
2 B 2
从输出中我们可以看到:
- 球队A有3行积分列大于15的记录
- 球队B有2行积分列大于15的记录。
你可以使用类似的语法来执行分组和计数的任何特定条件。