Reading — step 1 of 5
Learn
~1 min readFunctions
Functions are first-class in R. Define with function(args) body:
square <- function(x) {
x * x
}
print(square(5)) # 25
The last expression is the return value — return() is optional.
Named arguments and defaults:
greet <- function(name, greeting = "Hello") {
cat(greeting, ", ", name, "!\n", sep="")
}
greet("Ada") # Hello, Ada!
greet("Ada", greeting = "Hi") # Hi, Ada!
greet(name = "Ada") # Hello, Ada!
R uses lazy evaluation — arguments aren't evaluated until used. This means you can pass expressions that would error if always evaluated:
default_or <- function(x, fallback) if (is.null(x)) fallback else x
default_or(NULL, stop("unreachable")) # safe — fallback isn't evaluated
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…