简体   繁体   English

使用plyr的R中的频率

[英]Frequencies in R using plyr

In my data I have a categorical variable called gender which consists of two types Male or Female. 在我的数据中,我有一个名为性别的分类变量,它由两种类型的“男性”或“女性”组成。 I want to obtain their counts and percentages. 我想获得他们的数量和百分比。

For example, the data is such: 例如,数据是这样的:

Gender
M
F
M
F

I want the output to something like: 我希望输出为:

Gender  Count  Percentage
M        200      50%
F        200      50%

I tried doing this to give me percentages but it keeps giving me an error saying, "Object female not found". 我尝试这样做是为了给我百分比,但是它一直给我一个错误,说“找不到对象女性”。 Currently I have tried: 目前,我已经尝试过:

summarise(BirthData, "Frequencies"= count(BirthData,Gender), 
"Percent" = count(BirthData,Gender)/ sum(count(BirthData,Gender)))

What am I doing wrong? 我究竟做错了什么?

We can use table along with prop.table 我们可以将tableprop.table一起使用

t1 <- table(df1$Gender)
prop.table(t1)

Or if we need it in a data.frame with the specified format, 或者,如果我们需要使用具有指定格式的data.frame

transform(setNames(as.data.frame(table(df1$Gender)), c("Gender", 
          "Count")), Percentage = paste0(100*Count/sum(Count), "%"))
# Gender Count Percentage
#1    F   188       47%
#2    M   212       53%

data 数据

set.seed(49)
df1 <- data.frame(Gender = sample(c("M", "F"), 400, replace=TRUE), 
  stringsAsFactors=FALSE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM