A variable stores a value, which can be explicitly provided or a result of a calculation.
Choose the names of variables freely, optimally meaningful to represent the problem of interest.
Type the following lines in the Console
. Observe changes in the Environment
pane after each Enter.
gardenWidth <- 5
gardenLength <- 6
gardenArea <- gardenWidth * gardenLength
To find out what the value of a variable is, type its name:
gardenArea
[1] 30
A frequent error is to ask for a non-existing variable. Type to see the error:
gggardenArea
Error in eval(expr, envir, enclos): object 'gggardenArea' not found
The arrow symbol <-
is called the assignment operator:
x <- 5
Variable assignment is needed to store a result.
When there is no assignment, the result is printed to screen and lost.
For example, the sequence of statements below is the wrong way to “increase x by one”.
The result is calculated but it is not stored.
Type these commands line by line. Observe when value of x
changes in the Environment
pane:
x <- 5
x
[1] 5
x + 1
[1] 6
x
[1] 5
Here is the correct way to “increase x by one”.
Type these commands line by line. Observe when value of x
changes in the Environment
pane:
x <- 5
x
[1] 5
x <- x + 1
x
[1] 6
Remember: no assignment, no change.
The variables are stored in R memory and RStudio shows them in the Environment
pane.
When you close RStudio, all variables are lost.
We will learn how to write scripts to store commands used to calculate variables.
The scripts provide reproducibility.
They store not only the results of calculations, but also document how the results were calculated.
Variable names in R are case sensitive (all other symbols also).
Note that _
is allowed in variable names.
Numbers (not at the beginning) are allowed too.
Here are some examples (and each one is a different variable):
gardenLength <- 6
garden_length <- 6
gArDeNlEnGtH <- 6 # this is bad, don't use this
garden.length <- 6 # this leads to mistakes, don't use this
len1 <- 5
len2 <- 6
Choose meaningful variable names for readable scripts.
Naturally, there are some limitations. Do not use variable names:
@#!%$^()-+=!~?,<>}{][
for
, while
, repeat
, if
, else
, TRUE
, FALSE
, Inf
, NA
, NaN
RStudio provides autocomplete feature, useful for long variable names.
Start typing the first letters of a (variable) name and press Tab
.
Copyright © 2022 Biomedical Data Sciences (BDS) | LUMC