Last active
August 29, 2015 14:15
-
-
Save karawoo/6fec998c995e54c3e7d0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library("plyr") | |
library("dplyr") | |
### create some sample data | |
set.seed(20) | |
dat <- data.frame(lake = c(rep("Muddy", 6), rep("Clear", 6)), | |
host = c(rep(c("a", "b"), 6)), | |
var = sample(c(0, 1, 2), 12, replace = TRUE), | |
stringsAsFactors = FALSE) | |
### dplyr solution | |
dat %>% | |
group_by(lake, host) %>% | |
summarize(prop = mean(var != 0)) | |
### plyr solution | |
ddply(dat, .(lake, host), summarize, prop = mean(var != 0)) | |
### base R solution | |
aggregate(var ~ lake + host, data = dat, function(x) mean(x != 0)) | |
### to get proportions and numbers of observations at the same time with dplyr: | |
dat %>% | |
group_by(lake, host) %>% | |
summarize(prop = mean(var != 0 ), | |
count = n()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment