Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Say it in R with by, apply and friends
## 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)"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))
ddply(iris, "Species", function(x){
y <- subset(x, select= -Species)
apply(y, 2, mean)
ddply(iris, "Species", function(x) colMeans(subset(x, select= -Species)))
cast(melt(iris, id.vars='Species'),formula=Species ~ variable,mean)
summaryBy(Sepal.Length + Sepal.Width + Petal.Length + Petal.Width ~ Species, data=iris, FUN=mean)
sqldf("select Species, avg(Sepal_Length), avg(Sepal_Width),
avg(Petal_Length), avg(Petal_Width) from iris
group by Species")
iris.dt <- data.table(iris)
apply(iris3, c(3,2), mean)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment