R works with several data types and data structures, including:
Basic types
4.5 is a decimal number (type: numeric).4L is an integer (type: integer). Integers are a subset
of numeric values.TRUE or FALSE are Boolean values (type:
logical)." " or ' ' are text
(strings). They are stored as type: character.You can check the type of an object with class().
Variables store values and are a key component in programming. In R, a variable can store almost anything: a number, an object, a statistical result, a vector, a dataset, a model, or predictions. You can reuse a variable later by typing its name.
To create a variable, you assign a value to a name. Variable names
should not contain spaces; you can use _ to separate
words.
To assign a value, use <- (recommended) or
=.
Here is the syntax:
# Recommended assignment operator
name_of_variable <- value
# Also used sometimes (e.g., inside function calls)
name_of_variable = valueIn the console, you can run the following examples:
A vector is a one-dimensional sequence of values. You can create a
vector from any basic type. The simplest way to build a vector is using
c().
You can perform arithmetic operations on vectors element-by-element.
## [1] 3 7 11
In R, you can slice a vector using square brackets [].
For example, x[1:5] selects elements 1 to 5.
## [1] 1 2 3 4 5
Let’s look at basic arithmetic operators in R:
| Operator | Description |
|---|---|
|
|
Addition |
|
|
Subtraction |
|
|
Multiplication |
| / | Division |
| ^ | Exponentiation |
| %% | Modulo (remainder) |
Notes:
# are comments; R ignores
them.## prefix.Logical operators return TRUE or FALSE.
They are used to test conditions and filter values.
| Operator | Description |
|---|---|
| < | Less than |
| <= | Less than or equal to |
| > | Greater than |
| >= | Greater than or equal to |
| == | Exactly equal to |
| != | Not equal to |
| ! | Not x |
| x & y | x AND y (vectorised) |
| x | y | x OR y (vectorised) |
| isTRUE(x) | Test whether x is TRUE |
To select values that satisfy a condition, use:
# Create a vector from 1 to 10
logical_vector <- 1:10
# Test a condition (returns TRUE/FALSE for each element)
logical_vector > 5## [1] FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE
In the output above, R compares each element to the condition
logical_vector > 5. If the element is strictly greater
than 5, the result is TRUE; otherwise it is
FALSE.
To extract only the values that meet the condition, put the condition
inside [] after the vector.
## [1] 6 7 8 9 10
A work by Gianluca Sottile
gianluca.sottile@unipa.it