Functions in R Programming Language
Functions are central in R. We’ll learn about functions with a few different examples.
To run the program, save it as functions.R
and use Rscript
:
In R, functions are first-class objects, which means they can be assigned to variables, passed as arguments to other functions, and returned from functions.
R uses lexical scoping, which means that free variables in a function are looked up in the environment where the function was defined.
Unlike some other languages, R doesn’t require you to declare the types of function parameters or return values. This makes R more flexible but also means you need to be more careful about type consistency in your code.
R also supports default arguments, variable number of arguments, and named arguments, which we’ll explore in later examples.
There are several other features to R functions. One is the ability to return multiple values using lists or data frames, which we’ll look at next.