2 + 2[1] 4
Now that we know how to work with RStudio and scripts, we can start learning how R actually works.
R essentially works by creating objects and then using operators and functions to do things with those objects.
In this module, we will start with some of the most basic building blocks of the R language.
The first thing we need to do is open RStudio, open our intro-r-course project, and create a new R script.
Save the script inside the scripts folder as:
module-02.R
We will use this script throughout the module.
R basically works by giving it written instructions using commands or expressions.
A very simple R command can be:
If we type this into our script, nothing will happen until we tell R to run or evaluate the command.
To run a line of code, place your cursor on that line and:
Windows: Ctrl + Enter
Mac: Command + Enter
You can also click the Run button in RStudio.
If you want to run several lines at once, select the lines and then use the same shortcut.
Let’s start with something simple:
R should return:
[1] 4
When we run this line, the result appears in the Console.
In this case, R tells us that evaluating the command produced an object containing the number 4.
Remember: R works with objects.
We can also use parentheses to group operations:
R returns:
[1] 9.833333
Just as in regular mathematics, operations inside parentheses are evaluated first.
So far, the results of our operations appear in the Console, but as we continue running commands, those results disappear from view.
Most of the time, we will want to assign a result to an object so that we can use it again later.
In R, we usually assign something to an object using:
<-
For example:
We just created two objects, each containing a number.
Notice that R did not print anything in the Console.
The values were stored inside the objects.
To see what an object contains, simply run its name:
R returns:
[1] 56
The shortcut for writing <- in RStudio is:
Windows: Alt + -
Mac: Option + -
Try it!
You can choose almost any name you want for an object, but there are some important rules.
R is case-sensitive.
For example:
and:
are two different names.
If only big_number exists and you try:
R will return an error.
We should also avoid using accents or special characters in object names, file names, folder names, and column names. They may work in many cases, but differences in character encoding can sometimes create unnecessary problems.
Object names:
+, -, *, /, #, %, [ ], { }, ( ), or ~,mean.Most importantly, object names should tell us something about what the object contains.
Compare:
with:
The second name is much easier to understand when we return to the script later.
Common ways to write longer object names include:
or:
Throughout this course, we will mostly use snake_case:
Be careful when you reuse an object name.
Assigning something new to an existing object will overwrite its previous value.
For example:
returns:
[1] 56
But now let’s do this:
R now returns:
[1] "fifty six"
The original number 56 has been replaced.
R can store different types of information.
For now, we will focus on four basic types:
Later, we will combine these values into more complex data structures such as vectors, matrices, lists, and data frames.
Numeric objects contain numbers.
They can contain whole numbers or numbers with decimals.
Because these objects contain numbers, we can perform mathematical operations with them.
For example:
We can continue using the object we just created:
And we can keep combining objects and operations:
Or something more complicated:
| Operator | Operation |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
^ |
Power |
We can also compare values using relational operators.
Instead of returning a number, these comparisons return a logical value: TRUE or FALSE.
For example:
Another example:
And:
Notice that testing whether two values are equal requires two equal signs:
| Operator | Operation |
|---|---|
< |
Less than |
<= |
Less than or equal to |
> |
Greater than |
>= |
Greater than or equal to |
== |
Equal to |
!= |
Not equal to |
For example:
Character objects contain text.
Text in R must normally be placed inside quotation marks:
or:
For example:
We can also store complete phrases:
Now, what happens if we do this?
Although 69 looks like a number, the quotation marks tell R to treat it as text.
This means that we cannot use it directly for arithmetic:
R will return an error.
However, relational operators can also be used with character values.
For example:
In this case, R uses alphabetical order.
We can also compare text directly:
Remember that R is case-sensitive.
Another example:
Logical objects contain one of two values:
TRUE
FALSE
They basically represent whether a condition is met or not.
We can create a logical object directly:
Logical values are especially useful when we use relational operators.
For example:
We can also combine logical conditions.
For example, the | operator means OR:
because at least one of the two conditions is true.
We will use logical values much more later when we begin filtering and manipulating datasets.
Sometimes an observation or value does not exist or was not recorded.
In R, missing values are represented by:
NA
It is very important to understand that NA is not the same as zero.
Imagine that we are counting frogs in ponds.
A value of:
0
could mean:
We visited the pond and did not observe any frogs.
In contrast:
NA
could mean:
We never visited that pond, so we do not know how many frogs were there.
Those are very different situations.
We can create an object containing a missing value:
Missing values are extremely common in real datasets, and later we will learn how to identify and work with them.
Functions are predefined operations designed to perform a specific task.
Most R functions follow this general structure:
function_name(object)
For example, the function:
tells us what type of object we are working with.
Try:
Now try the object we created earlier:
We can also check a logical value:
And:
A bare NA is stored as a logical missing value by default. Later, when we work with datasets, we will see that missing values can also occur inside numeric, character, and other types of variables.
Functions receive information through arguments.
For example:
Here:
3.14159
is the value we want the function to use, and:
digits = 2
tells round() how many decimal places we want.
Different functions accept different arguments.
You do not need to memorize all of them.
R provides documentation for its functions.
For example:
or
will open the help page for round().
Learning R is not about memorizing every function and every argument.
Learning how to find the documentation you need is much more useful.
Many functions are already included when we install R. These are often referred to as base R functions.
However, a large part of R’s functionality comes from functions created by the community and distributed through packages.
To use functions from a package, we generally need to:
Let’s install a small package called beepr.
beepr allows R to make sounds.
Run:
Remember that you need an Internet connection to install a package.
You normally only need to install a package once on your computer.
Once the package is installed, we need to load it into our current R session.
Unlike install.packages(), we usually run library() every time we start a new R session and want to use that package.
Now we can use one of the functions included in beepr:
If everything worked correctly, your computer should make a sound.
There are thousands of R packages.
Most are available through a repository called CRAN, but packages can also be distributed in other ways.
The easiest way to find a package is often simply to search for what you want to do.
For example:
package for Shannon diversity index in R
A search like this will probably lead you to packages such as vegan.
The next step is then to learn how that package works by reading its documentation, examples, or tutorials.
This activity should take approximately 15–20 minutes.
Open your intro-r-course project and create a new script called:
practice-02.R
Save it inside the scripts folder.
Complete the following activities:
species containing the name of an animal species.station containing a camera station name such as "CT01".detections containing a number.detections is greater than 10.class() to check the type of each of the following:round().Your script could look something like this:
# Practice for Module 2
# Character objects
species <- "Raccoon"
station <- "CT01"
# Numeric object
detections <- 15
# Is the number of detections greater than 10?
detections > 10[1] TRUE
[1] 25
[1] 15
[1] 100
[1] 4
[1] "numeric"
[1] "character"
[1] "logical"
[1] "logical"
Your object names and values can be different.
The important thing is that you practice:
<-,
Comments
Sometimes we want to write notes in our script to remember what the code does.
If we simply write regular text into a script and try to run it, R will probably return an error because it will try to interpret our words as code.
To prevent this, we use the
#symbol.R returns:
Anything after
#on a line is considered a comment.Use comments frequently in your scripts.
Your future self will thank you.