Created
January 29, 2016 07:32
-
-
Save sudevschiz/cdd3f724471bcab0beb1 to your computer and use it in GitHub Desktop.
Example for sapply in R
This file contains 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
## Supposed you want to apply an operation to every element in a vector. Efficient way to do it in R is to use sapply / lapply | |
## Sample vector of 100 observation | |
x_vec <- rnorm(100) | |
## Need to find the absolute value of each element | |
x_abs <- sapply(x_vec,abs) | |
## The above implementation equivalent to doing x_abs <- abs(x_vec) | |
## But in case of userdefined functions, this is helpful | |
x_new <- sapply(x_vec,function(x) x > 2.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment