f(arg1, arg2, ...)
Prerequisites
Please make sure you have downloaded both
R
andRStudio
, as outlined in the previous lab.Please make sure you are familiar with the concepts of data types, data structures, and packages, along with the basics of programming outlined in Part 1.
Pre-Existing R
Functions
Recall, from Part 1, that functions in R
behave much like functions in mathematics. .
Given a function f()
that has been defined in R
, we call the function on inputs (aka arguments) arg1
, arg2
, … using the syntax
Keep in mind that each of the arguments could potentially be of different data types and/or structures, depending on how the function has been defined.
We have actually already seen and utilized several functions in R
! For example, we used the print()
function to print outputs; we also used the data.frame()
function to create a data frame.
Remember that you can always access the help file for a function with name function_name
using the syntax ?function_name
.
User-Defined Functions
To define a function with the name function_name
, we use the syntax:
<- function(arg1, arg2, ...) {
function_name <body of function>
}
For example,
<- function(x) {
sum_sq return(sum(x^2))
}
defined a function sum_sq
that returns the sum of the squared elements in a vector x
.
Vectorization
One of the key features of R
is that, by default, the vast majority of functions are vectorized. This means that functions, most of the time, are applied element-wise to vectors. For example, given a vector x
, we can add 2
to every element in x
by simply writing x + 2
:
<- c(1, 2, 3)
x + 2 x
[1] 3 4 5
If you want to vectorize a user-defined function, you can use the wrapper Vectorize()
.