3 + 5
[1] 8
12 / 7
[1] 1.714286
You can get output from R simply by typing math in the console:
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 <-
, 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 good practice to always use <-
for assignments.
In RStudio, typing Alt + - (push Alt at the same time as the - key) will write <-
in a single keystroke in a PC, while typing Option + - (push Option at the same time as the - key) does the same in a Mac.
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
, T
, mean
, data
, df
, 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, some popular style guides are Google’s, the tidyverse’s style and the Bioconductor style guide. The tidyverse’s is very comprehensive and may seem overwhelming at first. You can install the lintr
package to automatically check for issues in the styling of your code.
Objects vs. variables: What are known as
objects
inR
are known asvariables
in many other programming languages. Depending on the context,object
andvariable
can have drastically different meanings. However, in this lesson, the two words are used synonymously. For more information see here.
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:
weight_kg <- 55 # doesn't print anything
(weight_kg <- 55) # but putting parenthesis around the call prints the value of `weight_kg`
[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):
We can also change an object’s value by assigning it a new one:
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?
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 (more on that later). A function usually gets 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. Executing a function (‘running it’) is called calling the function. An example of a function call is:
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()
.
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)
or look at the help for this function using ?round
.
We see that if we want a different number of digits, we can type digits=2
or however many we want.
If you provide the arguments in the exact same order as they are defined you don’t have to name them:
And if you do name the arguments, you can switch their order:
It’s good practice to put the non-optional arguments (like the number you’re rounding) first in your function call, and to 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. By specifying the name of the arguments you are also safeguarding against possible future changes in the function interface, which may potentially add new arguments in between the existing ones.
The materials in this lesson have been adapted from work created by the HBC and Data Carpentry, as well as materials created by Laurent Gatto, Charlotte Soneson, Jenny Drnevich, Robert Castelo, and Kevin Rue-Albert. These are open access materials distributed under the terms of the Creative Commons Attribution license (CC BY 4.0), which permits unrestricted use, distribution, and reproduction in any medium, provided the original author and source are credited.
Comments
The comment character in R is
#
, anything to the right of a#
in a script will be ignored by R. It is useful to leave notes, and explanations in your scripts.RStudio makes it easy to comment or uncomment a paragraph: after selecting the lines you want to comment, press at the same time on your keyboard Ctrl + Shift + C. If you only want to comment out one line, you can put the cursor at any location of that line (i.e. no need to select the whole line), then press Ctrl + Shift + C.
What are the values after each statement in the following?