介绍
Description
count() lets you quickly count the unique values of one or more variables: df %>% count(a, b) is roughly equivalent to df %>% group_by(a, b) %>% summarise(n = n()). count() is paired with tally(), a lower-level helper that is equivalent to df %>% summarise(n = n()). Supply wt to perform weighted counts, switching the summary from n = n() to n = sum(wt).
add_count() and add_tally() are equivalents to count() and tally() but use mutate() instead of summarise() so that they add a new column with group-wise counts.
library(tidyverse)
glimpse(starwars)
#简单用法
starwars %>% count(species)
starwars %>% count(species, sort = TRUE)
starwars %>% count(sex, gender, sort = TRUE)#相当于table
starwars %>% count(birth_year, sort = TRUE)
starwars %>% count(birth_decade = round(birth_year, -1))
#count可以对最终结果进行加权
#构建数据集
df <- tribble(
~name, ~gender, ~runs,
"Max", "male", 10,
"Sandra", "female", 1,
"Susan", "female", 4
)
# 未加权:
df %>% count(gender)
# 加权后:
df %>% count(gender, wt = runs)
# tally() 函数比count等级低,这个函数认为
starwars %>% tally()
starwars %>% group_by(species) %>% tally()
# both count() 和 tally() 类似,都有添加变量的作用,注意权重的情况
df %>% add_count(gender, wt = runs)
df %>% add_tally(wt = runs)
df %>% add_count(gender)
网友评论