Reputation: 3181
I am producing a frequency table of row percentages in R using the following method:
df <- as.data.frame(c("Boy","Girl","Boy","Girl"))
colnames(df) <- "SEX"
df$GP <- c("A","A","B","B")
df$freq <- c(1,2,3,4)
tab <- as.data.frame.matrix(prop.table(table(df$GP, df$freq),1))
However, I would like to distinguish between frequencies by the variable "SEX". Is there a way to do this without splitting the dataframe by sex, creating two dataframes, one for boys and one for girls then merging together?
A three way frequency table table(df$GP, df$freq, df$SEX)
cannot be coerced into a data frame matrix. Also using exclude
such as table(df$GP, df$freq, df$SEX, exclude="Boy")
results in the same problem.
Is there an efficient way to do this?
Upvotes: 0
Views: 1386
Reputation: 1465
p_tabl <- prop.table(xtabs(freq~GP+SEX, data=df))
(as.data.frame(p_tabl))
Upvotes: 2