1/9
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai |
|---|
No analytics yet
Send a link to your students to track their progress
basic structure
my_func <- function(input1, input2){
result <- input1 * input2
return(result)
}
setting default arguments
greet <- function(name, greeting="Hello"){
return(paste(greeting, name))
}
greet("Sam") # uses default
greet("Sam", "Hi") # overrides default
returning multiple values
stats <- function(x){
return(list(mean=mean(x), sd=sd(x)))
}
out <- stats(1:100)
out$mean; out$sd
assign values to global env
assign("var_name", value, envir=.GlobalEnv)
if/ else conditions
if(condition){
# do this
} else if(other condition){
# do that
} else {
# fallback
}
Condition must be a single TRUE/FALSE. For vectors, use ifelse():
ifelse(x > 10, "big", "small") # vectorized version
apply functions
use instead of loops
faster and more readable
Move random number generation OUTSIDE the apply call.
lapply(list, FUN) # apply to list → returns list
sapply(list, FUN) # apply to list → returns vector
mapply(FUN, arg1, arg2) # multiple changing inputs
apply(matrix, 1, FUN) # apply across rows (1) or cols (2)
anonymous functions
sapply(my_list, function(x){ mean(x, na.rm=TRUE) })
to load multiple packages
sapply(c("dplyr","ggplot2","lubridate"), require, character.only=TRUE)
error handling
result <- try(some_function()) # won't crash loop on error
if("try-error" %in% class(result)){
# handle the error
} else {
# proceed normally
}
Use inside loops when one failure shouldn't stop the whole run. Track which iterations failed with a separate vector.
how much time
system.time({ your_code_here }) # how long does it take?
Vectorized operations (on whole vectors at once) are much faster than looping element by element in R.