Functions are first-class in R—define with function(args) { body }. Named arguments and defaults reduce boilerplate; return the last evaluated expression unless return() is used.
Defining functions
add <- function(a, b) {
a + b
}
greet <- function(name = "World") {
paste("Hello,", name)
}
Default arguments
scale_center <- function(x, center = TRUE) {
if (center) x - mean(x) else x
}
Avoid growing environments accidentally—document side effects in production code.
Important interview questions and answers
- Q: Implicit return?
A: The last expression in a function body is returned unless return() is called earlier. - Q: function vs <- function?
A: Both create functions; the assignment form is idiomatic:fn <- function() {}.
Self-check
- How do you set a default argument?
- What returns from a function if return() is omitted?
Pitfall: R functions return the last expression—use early return() when clarity helps.
Interview prep
- Default arguments?
Defined in the signature:
function(x, center = TRUE).