Reputation: 3158
so this is a simple question, and it's unclear to me what's going wrong with this plyr call.
library(plyr)
some silly data with a binomial outcome (y1
) and two four-level classifying factors(x1
and x2
):
df <- data.frame(x1 = sample(letters[1:4], 4000,T),
x2 = sample(LETTERS[5:8], 4000,T),
y1 = rbinom(n=4000,1,.5))
I want a table with the row proportions of each outcome--and i thought the following would work
foo <- ddply(df, .(x1,x2), function(i) prop.table(table(i$y1),1))
but instead it gives me:
head(foo)
x1 x2 0 1
1 a E 1 1
2 a F 1 1
3 a G 1 1
4 a H 1 1
5 b E 1 1
6 b F 1 1
which is clearly not what i'm looking for. What's my omission?
Upvotes: 2
Views: 1004
Reputation: 7475
try
foo<-ddply(df, .(x1,x2), function(i) prop.table(table(i$y1)))
> head(foo)
x1 x2 0 1
1 a E 0.5365854 0.4634146
2 a F 0.4936170 0.5063830
3 a G 0.5176471 0.4823529
4 a H 0.4568966 0.5431034
5 b E 0.4780702 0.5219298
6 b F 0.5617530 0.4382470
not sure if thats what you want
Upvotes: 4