As in other programming languages, you can store values into a variable to access it later. We do this by using the <-
operator which is a less-than sign <
followed by a dash -
- you can think of this as an arrow assigning a value to a name. So to store the value of 42
in a variable x
x <- 42
Note: we can also use the single equals sign =
instead of <-
, though <-
is preferred (for reasons we don’t want to go into).
You can print the value of a variable at any time just by typing its name in the console:
x
## [1] 42
Variable names in R can consist of any letters, numbers, and the full stop .
or underscore _
characters. However, variable names cannot start with a number or _
.
R Help: <-
Variables can take on a number of different types depending on what the value is that they represent. There are three main types of interest to us
1
or 3.14159
.TRUE
or FALSE
.''
or double quotes ""
, e.g. a package name, a file path, a label to a plot, etc.R can be used as a calculator to perform the usual simple arithmetic operations. The operators are:
+
addition-
subtraction*
multiplication/
division^
raise to the power.%%
modulus, e.g. 5 %% 3
is 2
%/%
integer division, e.g. 5 %/% 3
is 1
1 + 1
## [1] 2
6*7
## [1] 42
R Help: Arithmetic operators
For working with logical variables, R provides the usual ‘NOT,’ ‘AND,’ and ‘OR’ operators as:
!
logical ‘not’&
logical ‘and’|
logical ‘or’xor
‘exclusive or’ functionx <- TRUE
y <- FALSE
!x
## [1] FALSE
x & y
## [1] FALSE
x | y
## [1] TRUE
xor(x,y)
## [1] TRUE
R Help: Logical operators
A common source of logical variables is from the comparing two (or more) values. For example, we can use ‘<’ to test a pair of values:
3 < 4
## [1] TRUE
The result of such a comparison is a logical value.
R has a number of ways of comparing different values or variables. For numerical values, the comparison operators are:
<
less than>
greater than<=
less than or equal to>=
greater than or equal to==
equal to!=
not equal to.Note that to test for equality we use the equals sign twice ==
. Using only one equals sign would try to assign the value on the right to the variable on the left - this is one reason we prefer to use <-
to assign variables.
a <- 7
a==5
## [1] FALSE
a=5 ## oops
a
## [1] 5
R Help: comparisons