简体   繁体   中英

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

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

Or if we need it in a data.frame with the specified format,

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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