Created
March 4, 2015 21:01
-
-
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.
This file contains hidden or 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
| 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