Functions
A function is created with function(args) { body } and assigned to a name with <-, same as any other value — functions are not special syntax, they're ordinary values you happen to be able to call. Arguments can have default values, supplied with =, used whenever the caller doesn't pass that argument explicitly. A function's return value is the last expression it evaluates — there's no return keyword required, the same implicit-return style Ruby uses.
greet <- function(name, greeting = "Hello") {
paste(greeting, name)
}
print(greet("World"))
print(greet("R", "Hi"))
[1] "Hello World" [1] "Hi R"
greet("World") used the default greeting "Hello" since none was supplied; greet("R", "Hi") overrode it. Neither call needed an explicit return(paste(...)) — the function's single expression, paste(greeting, name), is automatically what comes back. Next: vectors vs. lists — list(), heterogeneous collections, and the real difference between [ ] and [[ ]].
Practice exercise
Write square <- function(x) that returns x^2 using an implicit return (no return keyword), then print square(7).