user-defined functions

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/9

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 1:55 AM on 4/24/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai

No analytics yet

Send a link to your students to track their progress

10 Terms

1
New cards

basic structure

my_func <- function(input1, input2){

result <- input1 * input2

return(result)

}

2
New cards

setting default arguments

greet <- function(name, greeting="Hello"){

return(paste(greeting, name))

}

greet("Sam") # uses default

greet("Sam", "Hi") # overrides default

3
New cards

returning multiple values

stats <- function(x){

return(list(mean=mean(x), sd=sd(x)))

}

out <- stats(1:100)

out$mean; out$sd

4
New cards

assign values to global env

assign("var_name", value, envir=.GlobalEnv)

5
New cards

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

6
New cards

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)

7
New cards

anonymous functions

  • sapply(my_list, function(x){ mean(x, na.rm=TRUE) })

8
New cards

to load multiple packages

sapply(c("dplyr","ggplot2","lubridate"), require, character.only=TRUE)

9
New cards

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.

10
New cards

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.