How to use dplyr to generate a frequency table

孤人 提交于 2019-11-30 11:04:05
library(dplyr)

df %>%
  count(Color, Gender) %>%
  group_by(Color) %>%          # now required with changes to dplyr::count()
  mutate(prop = prop.table(n))

# Source: local data frame [4 x 4]
# Groups: Color [3]
# 
#    Color Gender     n      prop
#   (fctr) (fctr) (int)     (dbl)
# 1   Blue      M     1 1.0000000
# 2    Red      F     2 0.6666667
# 3    Red     NA     1 0.3333333
# 4     NA      M     1 1.0000000

Updating per comment -- if you want to look at each variable separately, you will need to rearrange the dataframe first. You can accomplish this with tidyr:

library(tidyr)
library(dplyr)

gather(df, "var", "value", -RespondentID) %>%
  count(var, value) %>%
  group_by(var) %>%             # now required with changes to dplyr::count()
  mutate(prop = prop.table(n))

# Source: local data frame [6 x 4]
# Groups: var [2]
# 
#      var value     n  prop
#   (fctr) (chr) (int) (dbl)
# 1  Color  Blue     1   0.2
# 2  Color   Red     3   0.6
# 3  Color    NA     1   0.2
# 4 Gender     F     2   0.4
# 5 Gender     M     2   0.4
# 6 Gender    NA     1   0.2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!