Functions and apply
Define functions with function, default arguments, return a list, and apply a function to every element with sapply and lapply.
Runs in Zerethon IDE · R 4.5
Official R documentation ↗
main.R
greet <- function(name, greeting = "Hello") {
paste0(greeting, ", ", name, "!")
}
stats <- function(numbers) {
list(low = min(numbers), high = max(numbers), mean = mean(numbers))
}
print(greet("Ada"))
print(greet("Linus", greeting = "Hi"))
s <- stats(c(4, 8, 6))
cat(sprintf("%g %g %g\n", s$low, s$high, s$mean))
square <- function(x) x * x
print(square(1:4))
print(sapply(1:3, function(n) n * 10))
print(vapply(c("a", "bb", "ccc"), nchar, integer(1), USE.NAMES = FALSE))
print((\(x) x + 1)(9))
Output
[1] "Hello, Ada!" [1] "Hi, Linus!" 4 8 6 [1] 1 4 9 16 [1] 10 20 30 [1] 1 2 3 [1] 10
- A function returns the value of its last expression;
return()is only needed to leave early. - Return several values in a named
listand read them with$. - Most built-in functions already work on whole vectors, as
square(1:4)does — reach forsapplyonly when they do not. \(x) x + 1is a short way to writefunction(x) x + 1.