I need to calculate the percentage of counts of variables and put it in a vector
I have a frame as follows:
group <- c('A','A','A','B','B','B')
hight <- c('tall','tall','short','tall','short','short')
group hight
A tall
A tall
A short
B tall
B short
B short
If a run table(df) I get:
hight
group short tall
A 1 2
B 2 1
To calculate the percanteges
t=table(df)
percentages <- data.frame(group=c('A','B'), percent = c(t[1]/(t[1]+t[2]),t[3]/(t[3]+t[4])))
percentages
percent.vector <- c(t[1]/(t[1]+t[2]),t[3]/(t[3]+t[4]))
percent.vector
I get what I want:
group percent
1 A 0.3333333
2 B 0.6666667
[1] 0.3333333 0.6666667
... but I guess there is a better way to do it. I couldn't do this calculation for a higher range of groups.
How can I simplify the calculation of the percentages?
Thanks
round(prop.table(table(df)), 2)
– Rodrick