Skip to content

Instantly share code, notes, and snippets.

@doobwa
Created October 3, 2011 04:03
Show Gist options
  • Save doobwa/1258414 to your computer and use it in GitHub Desktop.
Save doobwa/1258414 to your computer and use it in GitHub Desktop.
dfapply: apply an expression to each row of a data.frame
# Chris DuBois
# October 2, 2011
# dfapply: apply an expression to each row of a data.frame
# This can be especially helpful when organizing experimental setups and you want to plot the results from a data.frame.
# s: data.frame, where each row has argument values
# expr: expression to evaluate on each row of s
# Returns a data.frame with columns created or changed according to expr.
dfapply <- function(s,expr) {
d <- lapply(1:nrow(s),function(i) {
e <- evalq(environment(), s[i,], parent.frame())
eval(expr, e)
as.data.frame(as.list(e))
})
return(do.call(rbind,d))
}
# Example where we want to evaluate fn(a,b) on each row of s.
fn <- function(a,b) a[1]+b[1]
s <- expand.grid(a=1:3,b=1:4)
expr <- expression({
x <- fn(a,b)
})
y1 <- dfapply(s,expr)
# Alternatively done with sapply. This approach gets annoying with more complicated examples.
x <- sapply(1:nrow(s),function(i) fn(s$a[i],s$b[i]))
y2 <- cbind(x,s)
stopifnot(all(y1==y2))
# Example where you can return (multiple) vectors for each row of the data.frame
xs <- seq(0,5,by=.01)
s <- expand.grid(a=0:5,b=1:4)
expr <- expression({
yhat <- a + b*xs
xs <- xs
})
yhats <- dfapply(s,expr)
head(yhats)
require(ggplot2)
qplot(xs,yhat,data=yhats,colour=factor(b),linetype=factor(a),geom="line")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment