Reputation: 127
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?
Upvotes: 0
Views: 681
Reputation: 886948
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%
set.seed(49)
df1 <- data.frame(Gender = sample(c("M", "F"), 400, replace=TRUE),
stringsAsFactors=FALSE)
Upvotes: 2