dplyr创建因子水平的总计百分比 [英] dplyr to create aggregate percentages of factor levels

查看:66
本文介绍了dplyr创建因子水平的总计百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用dplyr为每个州创建因子变量水平的比例?例如,我想添加一个变量来指示数据框内每个州内女性的百分比。

How do I use dplyr to create proportions of a level of a factor variable for each state? For example, I'd like to add a variable that indicates the percent of females within each state to the data frame.

# gen data
state <- rep(c(rep("Idaho", 10), rep("Maine", 10)), 2)
student.id <- sample(1:1000,8,replace=T)
gender <- rep( c("Male","Female"), 100*c(0.25,0.75) )  
gender <- sample(gender, 40)
school.data <- data.frame(student.id, state, gender)

这是我知道是错误的尝试,但可以让我访问以下信息:

Here's an attempt that I know is wrong, but gets me access to the information:

 middle %>%
   group_by(state, gender %in%c("Female")) %>%
   summarise(count = n()) %>%
   mutate(test_count = count)

我很难使用count和mutate函数,因此很难进一步了解。它的行为不符合我的预期。

I have a hard time with the count and mutate functions, which makes it hard to get much further. It doesn't behave as I'd expect.

推荐答案

要在现有数据框中添加新列:

To add a new column to your existing data frame:

school.data %>% 
    group_by(state) %>%
    mutate(pct.female = mean(gender == "Female"))

使用总结而不是变异,如果您只希望每个状态一行而不是在原始数据中添加一列。

Use summarize rather than mutate if you just want one row per state rather than adding a column to the original data.

school.data %>%
   group_by(state) %>%
   summarize(pct.female = mean(gender == "Female"))
# # A tibble: 2 x 2
#    state pct.female
#   <fctr>      <dbl>
# 1  Idaho       0.75
# 2  Maine       0.70

这篇关于dplyr创建因子水平的总计百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆