Skip to content

Instantly share code, notes, and snippets.

@leeper
Last active August 29, 2015 14:05
Show Gist options
  • Save leeper/7099f9450d00cb7aa750 to your computer and use it in GitHub Desktop.
Save leeper/7099f9450d00cb7aa750 to your computer and use it in GitHub Desktop.
Creating a simple by pipe operator
# function definition
`%by%` <- function(a,b){
s <- substitute(a)
l <- as.list(s)
p <- parse(text=s)
if(length(p)>2) {
l <- l[3:length(l)]
do.call("by", c(list(data=eval.parent(p[2]),
INDICES=b,
FUN=eval.parent(p[1])),
l))
} else
by(eval.parent(p[2]), INDICES=b, FUN=eval.parent(p[1]))
}
# some simple tests
set.seed(1)
n <- 100
d <- data.frame(y = rnorm(n),
x1 = sample(1:2, n, TRUE),
x2 = sample(1:2, n, TRUE))
# simple example
#by(d$y, list(d$x1), FUN=sd)
sd(d$y) %by% d$x1
# right-hand side list
#by(d$y, list(d$x1, d$x2), FUN=mean)
mean(d$y) %by% list(d$x1, d$x2)
# with subsetting
#by(d$y[1:30], list(d$x1[1:30]), FUN=sd)
sd(d$y[1:30]) %by% d$x1[1:30]
# missing data
d2 <- d
d2$y[sample(10, 1:n)] <- NA
#by(d2$y, list(d2$x1), FUN=mean, na.rm=TRUE)
mean(d2$y, na.rm=TRUE) %by% d2$x1
# using a `with` statement
#by(d2$x1, list(d2$x2), FUN=table)
table(d2$x1) %by% d2$x2
#with(d2, by(x1, list(x2), FUN=table))
with(d2, table(x1) %by% x2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment