如何使用dplyr生成频率表 [英] How to use dplyr to generate a frequency table
本文介绍了如何使用dplyr生成频率表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢创建一个在数据框中具有几列频率的表格。我正在复制下面我的数据框的一部分。
I like to create a table that has the frequency of several columns in my data frame. I am copying part of my data frame below.
该表应该具有颜色中的红色的频率(n和%),性别中具有F的频率。
The table is supposed to have frequency (both n and %) of "red" in Color and "F" in Gender.
我认为dplyr软件包可以做到这一点,但我无法理解。
I think that the dplyr package could do this but I cannot figure it out.
谢谢 -
RespondentID Color Gender
1 1503 Red F
2 1653 NA M
3 1982 Red F
4 4862 Red NA
15 4880 Blue M
推荐答案
library(dplyr)
df %>%
count(Color, Gender) %>%
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
每个注释更新 - 如果要单独查看每个变量,您将需要首先重新排列数据框。您可以使用 tidyr
完成此操作:
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) %>%
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
这篇关于如何使用dplyr生成频率表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文