5 Functions in R
We’ve learned how to use built-in R
functions like dnorm()
and pnorm()
to analyze distributions, but sometimes it’s going to be more helpful to be able to (A) do the math by hand or (B) code your function to do it. So, let’s learn how in the world you do that!
5.1 Coding your own function!
Functions
are machines that do a specific calculation using an input to produce a specific output.
Below, we’ll write an example function, called add(a, b)
.
This function takes two
numeric
values,a
andb
, asinputs
, and adds them together.Using
function()
, we’ll tellR
that our function contains two inputs,a
andb
.Then, using
{ ... }
, we’ll put the action we wantR
to do in there.The function can involve multiple operations inside it. But at the end, you need to print one final output, or put
return()
around your output.
## [1] 3
# This also works
add <- function(a, b){
# Assign output to a temporary object
output <- a + b
# Return the temporary object 'output'
return(output)
}
#
add(1, 2)
## [1] 3