sqrt()
5 Functions and objects
- Be able to use functions
- Be able to assign values to objects
5.1 Purpose and aim
In this section we’ll focus on functions and objects. We’ll learn how to use functions and how to create and access objects.
5.2 Functions
Functions perform specific operations. A function usually gets one or more inputs called arguments and returns a value. You can see it as a predefined script.
An example is:
This function returns the square root of a number. As such, it can only have a number as input, for example:
sqrt(9)
[1] 3
Functions can take different arguments. In the example above there was only one, but many functions allow you to specify more than one input. For example, let’s say we wanted to round a number.
We can use the round()
function:
round(10.232)
[1] 10
This returns a whole number. But what if we wanted to round it to one decimal? The round()
function has an argument called digits
that allows you to do just that. We separate the input and the argument with a comma.
round(10.232, digits = 1)
[1] 10.2
5.3 Objects
Often, you want to save the output of an operation for later use. In those cases we need to store that information somewhere. These are called objects. What happens is that we assign the output of the operation to an object.
To create an object, we need to give it a name followed by the assignment operator <-
, and the value we want to give to it.
For example:
<- 21 age
We can read the code as: the value 21 is assigned to the object age
. When you run this line of code the object you just created appears in your Environment
tab (top-right panel).
When assigning a value to an object, R does not print anything on the console. You can print the value by typing the object name in the console or by running it from within your script.
age
[1] 21
5.3.1 Using objects
The nice thing about storing values in objects is that you can use them for further operations. Look at the following example.
Let’s say we wanted to calculate double the age
:
* 2 age
[1] 42
We can also perform operations between variables:
<- 4
phd_length
+ phd_length age
[1] 25
Complete Exercise 5.4.1.
5.3.2 Object types
In the example above we only used numbers - these are very useful, since we can do calculations with them.
Numbers are just one type of data you may encounter. Although there are quite a few different types, the main ones include:
- numbers (e.g.
62
,55
,-27
) - text (e.g.
"bunny"
,"greenhouse"
,"binder"
) - logical (
TRUE
orFALSE
) - missing values (
NA
)
You might have noticed that the text values are in quotes (" "
). R requires all text to be within quotation marks. That’s the way it recognises it as text (also sometimes referred to as a string).
The logical values are binary: they’re either true or false. In R these true/false designations are represented by TRUE
and FALSE
. Note that they are case-sensitive.
Missing values are specifically encoded as such in R. You’ll find that this is a really useful feature, because it makes missing values explicit. They are encoded with NA
.
You will notice that, in RStudio, the TRUE
, FALSE
and NA
values are coloured light blue. This is because they have special meaning to R.
This also means that we shouldn’t use these in a different context. For example, it’s a bad idea to create an object named TRUE
, since it would really confuse R.
There are other names that have special meaning, but don’t worry too much about it for now. Generally, if you accidentally choose a name for an object that has special meaning, it’ll quickly becomes clear because your code might stop working.
5.3.3 Vectors
Vectors are the building block of most programming languages. They are containers for a sequence of data elements. That may sound a bit cryptic, so let’s illustrate this with some examples.
In the examples above we stored a single value in an object. But quite often we work with more than just one data point. The way that we group these together into a vector is by using the c()
function.
The c()
or concatenate / combine function does what it says on the tin: it combines multiple values together. Have a look at the following set of examples:
Numbers:
<- c(12, 22, 98, 61)
vec_num
vec_num
[1] 12 22 98 61
Text:
<- c("felsic", "intermediate", "mafic", "ultramafic")
vec_text
vec_text
[1] "felsic" "intermediate" "mafic" "ultramafic"
In case you are wondering, these are different types of lava.
Mixed types:
<- c("tree", "leaf", 31, NA, 22)
vec_mixed
vec_mixed
[1] "tree" "leaf" "31" NA "22"
You can also combine vectors together, for example:
c(vec_num, vec_mixed)
[1] "12" "22" "98" "61" "tree" "leaf" "31" NA "22"
Often, not all data types are equal. We won’t go into too much detail here, but it’s important to keep in mind that:
the presence of text in a vector leads to all the elements being converted to text!
Complete Exercise 5.4.2.
5.4 Exercises
5.4.1 Dealing with objects
Level:
- Create an object
day_temp
containing the current temperature (yes, you can guess!) - Create an object
weather
containing the valuesraining
,cloudy
,sunny
<- 21
day_temp
<- c("raining", "cloudy", "sunny") weather
5.4.2 Vectors
Level:
Create the following vectors:
- A vector
vec_1
containing 3 numbers - A vector
vec_2
with two numbers and two words - A vector
vec_3
with two numbers, a missing value, two words and a TRUE/FALSE outcome
Look at the content of the vectors. Is there anything you notice?
<- c(31, 8, 92)
vec_1
<- c(77, "hedgehog", "cloud", 33)
vec_2
<- c(23, 66, NA, "bob", "jeff", FALSE) vec_3
You might have noticed that in vec_2
and vec_3
every value is now within quotes. That’s because as soon as there is any text in a vector, R automatically converts all elements in the vector to text.
5.5 Summary
- Functions perform a specific set of operations
- Objects allow you to store value that can be accessed later