5 R Basics
5.1 Creating objects in R
You can get output from R simply by typing math in the console:
## [1] 8
## [1] 1.714286
However, to do useful and interesting things, we need to assign values to objects. To create an object, we need to give it a name followed by the assignment operator <-
or =
, and the value we want to give it:
<-
is the assignment operator. It assigns values on the right to objects on the left. So, after executing x <- 3
, the value of x
is 3
. The arrow can be read as 3 goes into x. For historical reasons, you can also use =
for assignments, but not in every context. Because of the slight differences in syntax, it is best practice to always use <-
for assignments.
Objects can be given any name such as x
, current_temperature
, or subject_id
. You want your object names to be explicit and not too long.
They cannot start with a number (2x
is not valid, but x2
is). R is case sensitive (e.g., weight_kg
is different from Weight_kg
).
There are some names that cannot be used because they are the names of fundamental functions in R (e.g., if
, else
, for
, see here for a complete list). In general, even if it’s allowed, it’s best to not use other function names (e.g., c
, mean
, data
, weights
). If in doubt, check the help to see if the name is already in use. It’s also best to avoid dots (.
) within an object name as in my.dataset
. There are many functions in R with dots in their names for historical reasons, but because dots have a special meaning in R (for methods) and other programming languages, it’s best to avoid them. It is also recommended to use nouns for object names, and verbs for function names.
It’s important to be consistent in the styling of your code (where you put spaces, how you name objects, etc.). Using a consistent coding style makes your code clearer to read for your future self and your collaborators. In R, three popular style guides are Google’s, Jean Fan’s and the tidyverse’s. This may seem overwhelming at first. My suggestion is to focus on what makes sense to you, and that you are using naming conventions that will help you to remember what is stored in each object. Try and be consistent with spacing and capitalization (or not) — your future self will thank you.
5.2 Objects vs. variables
What are known as objects
in R
are known as variables
in many other programming languages. In this lesson, the two words are used synonymously. For more information see https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Objects
When assigning a value to an object, R does not print anything. You can force R to print the value by using parentheses or by typing the object name.
## [1] 55
## [1] 55
Now that R has weight_kg
in memory, we can do arithmetic with it. For instance, we may want to convert this weight into pounds (weight in pounds is 2.2 times the weight in kg):
## [1] 121
We can also change an object’s value by assigning it a new one:
## [1] 126.5
This means that assigning a value to one object does not change the values of other objects For example, let’s store the animal’s weight in pounds in a new object, weight_lb
:
and then change weight_kg to 100.
What do you think is the current content of the object weight_lb
? 126.5 or 220?
5.3 Functions and their arguments
Functions are “canned scripts” that automate more complicated sets of commands including operations assignments, etc. Many functions are predefined, or can be made available by importing R packages.
A function usually takes one or more inputs called arguments. Functions often (but not always) return a value. A typical example would be the function sqrt()
. The input (the argument) must be a number, and the return value (in fact, the output) is the square root of that number.
You can think of a function call generally as
do_this(to_that)
do_that(to_this, to_that, with_those)
Executing a function (‘running it’) is called calling the function. An couple of examples of function calls are:
## [1] "hello world"
## [1] 3
Here, the value of a
is given to the sqrt()
function, the sqrt()
function calculates the square root, and returns the value which is then assigned to the object b
. This function is very simple, because it takes just one argument.
The return ‘value’ of a function need not be numerical (like that of sqrt()
), and it also does not need to be a single item: it can be a set of things, or even a dataset. We’ll see that when we read data files into R.
Arguments can be anything, not only numbers or filenames, but also other objects. Exactly what each argument means differs per function, and must be looked up in the documentation (see below). Some functions take arguments which may either be specified by the user, or, if left out, take on a default value: these are called options. Options are typically used to alter the way the function operates, such as whether it ignores ‘bad values’, or what symbol to use in a plot. However, if you want something specific, you can specify a value of your choice which will be used instead of the default.
Let’s try a function that can take multiple arguments: round()
.
## [1] 3
Here, we’ve called round()
with just one argument, 3.14159
, and it has returned the value 3. That’s because the default is to round to the nearest whole number. If we want more digits we can see how to do that by getting information about the round function. We can use args(round)
to find what arguments it takes, or look at the help for this function using ?round
.
## function (x, digits = 0)
## NULL
We see that if we want a different number of digits, we can type digits = 2
or however many we want.
## [1] 3.14
If you provide the arguments in the exact same order as they are defined you don’t have to name them:
## [1] 3.14
And if you do name the arguments, you can switch their order:
## [1] 3.14
It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to then specify the names of all optional arguments. If you don’t, someone reading your code might have to look up the definition of a function with unfamiliar arguments to understand what you’re doing.
EXERCISE 5.3
Compute the golden ratio in a single line of code. One approximation of the golden ratio can be found by taking the sum of 1 and the square root of 5, and dividing by 2. Compute the golden ratio to 3 digits of precision using the sqrt()
and round()
functions. Hint: you can place one function inside of another.
5.4 Data types in R
So far we have been storing integer values in the above examples, now lets look at other data types present in R. There are several data types such as integer, string, etc. The operating system allocates memory based on the data type of the variable and decides what can be stored in the reserved memory.
There are the following data types which are used in R programming:
Data type | Example | Description |
---|---|---|
Logical | True, False | It is a special data type for data with only two possible values which can be construed as true/false. |
Numeric | 12,32,112,5432 | Decimal value is called numeric in R, and it is the default computational data type. |
Integer | 3L, 66L, 2346L | Here, L tells R to store the value as an integer, |
Complex | Z=1+2i, t=7+3i | A complex value in R is defined as the pure imaginary value i. |
Character | ‘a’, ‘“good’”, “TRUE”, ’35.4’ | In R programming, a character is used to represent string values. We convert objects into character values with the help ofas.character() function. |
Raw | A raw data type is used to holds raw bytes. |
5.5 Data structures in R
R has six types of basic data structures. We can organize these data structures according to their dimensions(1d, 2d, nd). We can also classify them as homogeneous or heterogeneous (can their contents be of different datatypes or not).
Homogeneous data structures are ones that can only store a single type of data (numeric, integer, character, etc.).
Heterogeneous data structures are ones that can store more than one type of data at the same time.
R does not have 0 dimensional or scalar type. Variables containing single values are vectors of length 1.
R has the following basic data structures:
- Vector (1d,homegenous)
- List (heterogeneous)
- Matrix (2d, homogeneous)
- Data frame (tibble) (2d, heterogeneous)
- Array (3d,homogeneous)
5.6 Vectors
A vector is the most common and basic data type in R, and is pretty much the workhorse of R. A vector is a collection of values that are all of the same type (numeric, character, etc.). We can assign a series of values to a vector using the c()
function. For example we can create a vector of animal weights and assign it to a new object weight_g
:
## [1] 50 60 65 82
A vector can also contain characters:
## [1] "mouse" "rat" "dog"
The quotes around “mouse”, “rat”, etc. are essential here. Without the quotes R will assume objects have been created called mouse
, rat
and dog
. As these objects don’t exist in R’s memory, there will be an error message.
There are many functions that allow you to inspect the content of a vector. length()
tells you how many elements are in a particular vector:
## [1] 4
## [1] 3
An important feature of a vector, is that all of the elements are the same type of data. The function class()
indicates the class (the type of element) of an object:
## [1] "numeric"
## [1] "character"
The function str()
provides an overview of the structure of an object and its elements. It is a useful function when working with large and complex objects:
## num [1:4] 50 60 65 82
## chr [1:3] "mouse" "rat" "dog"
You can use the c()
function to add other elements to your vector:
weight_g <- c(weight_g, 90) # add to the end of the vector
weight_g <- c(30, weight_g) # add to the beginning of the vector
weight_g
## [1] 30 50 60 65 82 90
In the first line, we take the original vector weight_g
, add the value 90 to the end of it, and save the result back into weight_g
. Then we add the value 30
to the beginning, again saving the result back into weight_g
.
We can do this over and over again to grow a vector, or assemble a dataset. As we program, this may be useful to add results that we are collecting or calculating.
5.7 Indexing vectors
If we want to extract one or several values from a vector, we must provide one or several indices in square brackets. For instance:
## [1] "rat"
## [1] "mouse" "rat" "dog"
## [1] "rat" "cat"
R indices start at 1. Programming languages like Fortran, MATLAB, Julia, and R start counting at 1, because that’s what human beings typically do. Languages in the C family (including C++, Java, Perl, and Python) count from 0 because reasons.
5.8 Conditional subsetting
Another common way of subsetting is by using a logical vector. TRUE
will select the element with the same index, while FALSE
will not:
## [1] 21 39 54
Typically, these logical vectors are not typed by hand, but are the output of other functions or logical tests. For instance, if you wanted to select only the values above 50:
## [1] FALSE FALSE FALSE TRUE TRUE
## [1] 54 55
You can combine multiple tests using & (both conditions are true, AND) or | (at least one of the conditions is true, OR):
## [1] 21 54 55
## numeric(0)
Here, <
stands for “less than”, >
for “greater than”, >=
for “greater than or equal to”, and ==
for “equal to”. The double equal sign ==
is a test for numerical equality between the left and right hand sides, and should not be confused with the single =
sign, which performs variable assignment (similar to <-
).
Operator | Description |
---|---|
< |
less than |
<= |
less than or equal to |
> |
greater than |
>= |
greater than or equal to |
== |
equal to |
!= |
not equal to |
!x |
not x |
a|b |
a or b |
a&b |
a and b |
A common task is to search for certain strings in a vector. One could use the “or” operator | to test for equality to multiple values, but this can quickly become tedious. The function %in%
allows you to test if any of the elements of a search vector are found:
animals <- c("mouse", "rat", "dog", "cat")
animals[animals == "cat" | animals == "rat"] # returns both rat and cat
## [1] "rat" "cat"
## [1] FALSE TRUE TRUE TRUE
## [1] "rat" "dog" "cat"
The which()
function returns the indices of any item that evaluates as TRUE in our comparison:
## [1] 4
5.9 Missing data
As R was designed to analyze datasets, it includes the concept of missing data (which is uncommon in other programming languages). Missing data are represented in vectors as NA
.
When doing operations on numbers, most functions will return NA
if the data you are working with include missing values. This feature makes it harder to overlook the cases where you are dealing with missing data. You can add the argument na.rm = TRUE to calculate the result while ignoring the missing values.
## [1] NA
## [1] NA
## [1] 4
## [1] 6
If your data include missing values (and that’s probably all of us!), you may want to become familiar with the functions is.na()
, and na.omit()
. See below for examples.
## [1] 2 4 4 6
## [1] 2 4 4 6
## attr(,"na.action")
## [1] 4
## attr(,"class")
## [1] "omit"