【问题标题】:Is there a way to divide answers of group_by summary statistics in R?有没有办法在 R 中划分 group_by 汇总统计的答案?
【发布时间】:2020-03-03 23:37:08
【问题描述】:

我正在尝试对来自三个向量的数据进行子集化,然后将算术应用于汇总统计信息,但我遇到了 count() 问题。下面是使用 (summarise, dplyr) 的摘要,但我希望它以未过滤 (X_age65yr) 的百分比形式返回。
例如,阿拉巴马州的过滤计数结果为 1667,总计数为 2411。我希望阿拉巴马州和所有后续州按总数返回过滤计数,或 1667/2411 = .6914 或 69.14%

cthigh <- brfss2013 %>% filter(bphigh4 == "Yes", !is.na(X_age65yr),X_age65yr == "Age 65 or older") %>%
   group_by(X_state) %>% summarise(count = n())

cthigh
# A tibble: 53 x 2
   X_state              count
   <fct>                <int>
 1 Alabama               1667
 2 Alaska                 507
 3 Arizona                930
 4 Arkansas              1352
 5 California            1817
 6 Colorado              2302
 7 Connecticut           1488
 8 Delaware              1123
 9 District of Columbia  1032
10 Florida               8924
# ... with 43 more rows

ctall <- brfss2013 %>% filter(!is.na(X_age65yr),X_age65yr == "Age 65 or older") %>% 
    group_by(X_state) %>% summarise(count= n())

ctall
# A tibble: 53 x 2
   X_state              count
   <fct>                <int>
 1 Alabama               2411
 2 Alaska                 864
 3 Arizona               1578
 4 Arkansas              2069
 5 California            3111
 6 Colorado              4067
 7 Connecticut           2362
 8 Delaware              1786
 9 District of Columbia  1683
10 Florida              14245
# ... with 43 more rows

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    您可以统计bphigh4 == "Yes"的数量,然后除以每个X_state中的行数得到比率。

    library(dplyr)
    
    brfss2013 %>% 
      filter(!is.na(X_age65yr) & !is.na(bphigh4),X_age65yr == "Age 65 or older") %>%
      group_by(X_state) %>% 
      summarise(count = sum(bphigh4 == "Yes")/n() * 100)
    

    【讨论】:

    • 抱歉耽搁了;我研究了你的解决方案 Ronak,我得到了所有的 NA,所以在我为 bphigh4 应用了一个额外的 !is.na 之后,它起作用了。谢谢!
    • @KurtRecker 好的,我试图根据您的尝试帮助您。我没有您的数据来验证是否需要额外的!is.na(bphigh4)
    • 当然。我只是为了交流而澄清。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多