Created
January 28, 2012 14:15
-
-
Save mages/1694442 to your computer and use it in GitHub Desktop.
Say it in R with by, apply and friends
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
## Markus Gesmann, January 2012 | |
## Please install the following R packages first: | |
## data.table, doBy, plyr, reshape, sqldf, e.g. via | |
## install.packages(c("data.table", "doBy", "plyr", "reshape", "sqldf")) | |
f <- function(x) x^2 | |
sapply(1:10, f) | |
do.call("rbind", as.list( | |
by(iris, list(Species=iris$Species), function(x){ | |
y <- subset(x, select= -Species) | |
apply(y, 2, mean) | |
} | |
))) | |
iris.x <- subset(iris, select= -Species) | |
iris.s <- subset(iris, select= Species) | |
aggregate(iris.x, iris.s, mean) | |
aggregate( . ~ Species, iris, mean) | |
apply(iris.x, 2, function(x) tapply(x, iris.s, mean)) | |
sapply(split(iris.x, iris.s), function(x) apply(x, 2, mean)) | |
library(plyr) | |
ddply(iris, "Species", function(x){ | |
y <- subset(x, select= -Species) | |
apply(y, 2, mean) | |
}) | |
ddply(iris, "Species", function(x) colMeans(subset(x, select= -Species))) | |
library(reshape) | |
cast(melt(iris, id.vars='Species'),formula=Species ~ variable,mean) | |
library(doBy) | |
summaryBy(Sepal.Length + Sepal.Width + Petal.Length + Petal.Width ~ Species, data=iris, FUN=mean) | |
library(sqldf) | |
sqldf("select Species, avg(Sepal_Length), avg(Sepal_Width), | |
avg(Petal_Length), avg(Petal_Width) from iris | |
group by Species") | |
library(data.table) | |
iris.dt <- data.table(iris) | |
iris.dt[,lapply(.SD,mean),by="Species",.SDcols=1:4] | |
apply(iris3, c(3,2), mean) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment