Functions are actions we can perform. R provides a number of functions, and you’ve actually been using a few of them even though you maybe didn’t realize!
We call, or use, these functions by stating the name of the function and following it with an opening and closing parentheses: ie.
functionName(). In addition, between the parenthesis, we usually pass in an argument, or a value that the function uses to conduct an action, i.e.
Does that syntax look a little familiar? When we have used
print() we’re calling the
c() function! Let’s see
print() and some real functions in action!
sort(c(2,4,10,5,1)); # Outputs c(1,2,4,5,10) length(c(2,4,10,5,1)); # Outputs 5 sum(5,15,10) #Outputs 30
Let’s look at each of the lines above:
- On the first line, the
sort()function is called with a parameter of the vector
c(2,4,10,5,1). The result is a sorted vector
c(1,2,4,5,10)with the values in ascending order.
- On the second line, we called a function we’ve seen before:
length()and it returned the value 5 because there were five items in the vector.
- On the third line, we called a function
sum()which added up all of the arguments we passed to it.
Understanding how to call a function and what arguments it needs is a fundamental part of leveraging R as a tool to conduct analysis. Let’s practice calling some useful functions!
unique() function takes a vector argument and returns a vector with only the unique elements in that vector (removing all duplicates).
- Call this function and pass in the argument
- Save that result inside a variable named
unique_valsvariable so you can see what is inside the vector with only unique values.
sqrt() square root of the number 49 by calling the function with the specified argument. Save the result inside a variable named
solution variable so you can see confirm
sqrt() computed the square root correctly.
floor() function rounds a decimal down to the next integer, and the
ceiling() function will round up to the next integer. Call both functions on the number 3.14, and save each result inside two new variables you create:
Print both variables so you can see what’s in them!