How to get proportions and counts of a data frame in r
r
Solution
Try installing plyr and running
library(plyr)
df <- data.frame(x1=c(1, 1, 0, 0, 1, 0),
label=c("a", "a", "b", "a", "c", "c"))
ddply(df, .(label), summarize, prop = mean(x1), count = length(x1))
# label prop count
# 1 a 0.6666667 3
# 2 b 0.0000000 1
# 3 c 0.5000000 2
which under the hood applies a split/apply/combine method similar to this in base R:
do.call(rbind, lapply(split(df, df$x2),
with, list(prop = mean(x1),
count = length(x1))))
Problem
I have a data frame like the one below, but with a lot more rows ``` > df<-data.frame(x1=c(1,1,0,0,1,0),x2=c("a","a","b","a","c","c")) > df x1 x2 1 1 a 2 1 a 3 0 b 4 0 a 5 1 c 6 0 c ``` From `df` I want a data frame where the rows are the unique values of `df$x2` and col1 is the proportion of 1s associated with each letter, and col2 is the count of each letter. So, my output would be ``` > getprops(df) prop count a .6666 3 b 0 1 c 0.5 2 ``` I can think of some elaborate, dirty ways to do this, but I'm looking for something short and efficient. Thanks