Skip to content

Instantly share code, notes, and snippets.

@sudevschiz
Created January 29, 2016 07:32
Show Gist options
  • Save sudevschiz/cdd3f724471bcab0beb1 to your computer and use it in GitHub Desktop.
Save sudevschiz/cdd3f724471bcab0beb1 to your computer and use it in GitHub Desktop.
Example for sapply in R
## 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