使用 dplyr 我正在为两个类别生成一个简单的汇总表:

# Data
data("mtcars")
# Lib
require(dplyr)
# Summary
mt_sum <- mtcars %>%
  group_by(am, gear) %>%
  summarise(n = n()) %>%
  spread(key = am, value = n)

这产生了预期的结果:
Source: local data frame [3 x 3]

   gear     0     1
  (dbl) (int) (int)
1     3    15    NA
2     4     4     8
3     5    NA     5

在生成的表中,我想添加一组包含行百分比而不是当前可用总数的列。

预期结果

我希望我的 table 看起来像这样:
   gear     0     1   0per   1per
1     3    15    NA   100%
2     4     4     8   33%    67%
3     5    NA     5          100%

尝试

我试图通过添加代码来实现以下目标:
mt_sum <- mtcars %>%
  group_by(am, gear) %>%
  summarise(n = n()) %>%
  spread(key = am, value = n) %>%
  mutate_each(funs(./rowSums(.)))

但它返回以下错误:



因此我的问题是: 如何在 dplyr 中添加带有行百分比值的额外列?

侧分
  • 我更喜欢空白值而不是 NAs
  • 可以使用 CrossTable 中的 gmodels 轻松构建该表,但我想留在 dplyr 中,因为我想在一个地方保留尽可能多的转换
  • 最佳答案

    我认为这就是你需要的:

    # Data
    data("mtcars")
    # Lib
    require(dplyr)
    require(tidyr)
    require(scales) #for percent
    # Summary
    mtcars %>%
      group_by(am, gear) %>%
      summarise(n = n()) %>%
      spread(key = am, value = n) %>%
      #you need rowwise because this is a rowwise operation
      rowwise %>%
      #I find do to be the best function for ad-hoc things that
      #have no specific dplyr function
      #I use do below to calculate the numeric percentages
      do(data.frame(.,
                    per0 = .$`0` / sum(.$`0`, .$`1`, na.rm=TRUE),
                    per1 = .$`1` / sum(.$`0`, .$`1`, na.rm=TRUE))) %>%
      #mutate here is used to convert NAs to blank and numbers to percentages
      mutate(per0 = ifelse(is.na(per0), '', percent(per0)),
             per1 = ifelse(is.na(per1), '', percent(per1)))
    

    输出:
    Source: local data frame [3 x 5]
    Groups: <by row>
    
       gear    X0    X1  per0  per1
      (dbl) (int) (int) (chr) (chr)
    1     3    15    NA  100%
    2     4     4     8 33.3% 66.7%
    3     5    NA     5        100%
    

    关于r - 在dplyr中按组获得总和后计算具有行百分比的列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34069576/

    10-12 17:33
    查看更多