Functions
Functions in R are written with function(), can take default argument values, and automatically return their last evaluated expression — an explicit return() is optional.
Defining and calling a function
R square.R
square <- function(x) {
x^2
}
square(5)
Console
[1] 25
There's no return() here — x^2 is the last (and only) expression evaluated inside the function body, so its value is what gets handed back automatically.
Default arguments
R greet.R
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
greet("Ava")
greet("Sam", "Hi")
Console
[1] "Hello Ava" [1] "Hi Sam"
paste() joins its arguments into one string with a space between them by default. Calling greet("Ava") without a second argument falls back to greeting = "Hello"; supplying one, as in greet("Sam", "Hi"), overrides it.
Note:
return() still works and is commonly used for an early exit from the middle of a function, but at the very end of a function body it's redundant — whatever the last line evaluates to is returned either way. Many R style guides actually prefer leaving it off at the end, exactly like the square() example above.