Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save AndrewLJackson/aed27dfb9ad494deef5c to your computer and use it in GitHub Desktop.

Select an option

Save AndrewLJackson/aed27dfb9ad494deef5c to your computer and use it in GitHub Desktop.
An example of how to use mapply() to evaluate a function requiring more than one input over a matrix or array.
X <- cbind(1:5, 6:10)
G <- 1:5
my.fun <- function(x,y){return(x+y)}
# ----------------------------------
# Loop example
loop.output <- double(length(G))
for (i in 1:length(G)){
loop.output[i] <- my.fun(X[i,1], X[i,2])
}
print(loop.output)
# ----------------------------------
# can we do this with aggregate()
# or tapply() or similar instead?
# YES! we can.. with mapply()
mapply.output <- mapply(my.fun, X[,1], X[,2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment