Module lessons (1/2)
Variables, Vectors and Recycling
Fundamentals of R: everything is a vector
Understand why in R even a single number like 10 is a vector of length 1.
Unlike Python or JavaScript, where x = 10 is a primitive scalar and [10, 20] is a separate list, in R every atomic value is a vector. The number 10 is also printed in the console as [1] 10: that [1] indicates the index of the first element of the vector.
This design choice makes R extraordinarily concise for data analysis: mathematical and logical operations automatically act on everything together without writing manual loops.
Assignment with <- vs =
In R the assignment arrow <- associates a name in the current environment (x <- 10). The = operator should be reserved for named parameters within function calls, such as seq(from = 1, to = 10, by = 2).
Example 1 — Variables and arithmetic expressions
base_price <- 120
vat_rate <- 0.22
gross_price <- base_price * (1 + vat_rate)
cat("Net:", base_price, "| Gross:", gross_price, "\n")
# Net: 120 | Gross: 146.4Vectors, sequences and 1-based indexing
The c() (combine) function concatenates values of the same type into a single vector. To generate regular intervals you can use the operator : (step 1) or seq(from, to, by).
| Function / Syntax | Main purpose | Example in R | Result |
|---|---|---|---|
c(a, b, c) | Combine values into a vector | c(10, 20, 30) | 10 20 30 |
1:5 | Whole sequence at step 1 | 3:6 | 3 4 5 6 |
seq(from, to, by) | Sequence with customized step | seq(0, 10, by = 5) | 0 5 10 |
rep(val, times) | Repeats a value or vector | rep(1, times = 3) | 1 1 1 |
v[1] | First element (index 1, never 0) | c(10, 20, 30)[1] | 10 |
v[-2] | The entire vector excluding the 2nd element | c(10, 20, 30)[-2] | 10 30 |
Example 2 — Creation, positive slicing and negative indices
daily_visits <- c(140, 185, 160, 210, 195)
first_day <- daily_visits[1]
midweek <- daily_visits[2:4]
without_monday <- daily_visits[-1]
print(first_day) # [1] 140
print(midweek) # [1] 185 160 210
print(without_monday) # [1] 185 160 210 195Vectorized Arithmetic and Vector Recycling
When you apply +, *, -, or > between two vectors, R operates element by element. If one vector is shorter than the other, R recycles the short vector by repeating it from the beginning until it covers the length of the longer vector.
- Clean recycling: length
4combined with1or2(exact multiple, no warning). - Unbalanced recycling: length
5combined with2or3still produces a result but prints a Warning (longer object length is not a multiple of shorter object length).
Explore R's behavior live in the interactive experiment below:
Example 3 — Vector operations and practical recycling
prices <- c(100, 200, 300, 400)
# Riciclaggio di lunghezza 2 su lunghezza 4 (alternanza 10% e 20% di sconto)
multipliers <- c(0.9, 0.8)
discounted <- prices * multipliers
print(discounted)
# [1] 90 160 270 320Example 4 — Vectors with names (names) and selection by label
You can assign descriptive names to each position with names(v) <- c(...): this way you can extract values both by position and by textual key.
revenue <- c(1200, 1450, 980)
names(revenue) <- c("Jan", "Feb", "Mar")
print(revenue["Feb"])
# Feb
# 1450Test yourself: guided exercises
Assign the value 10 to the variable x and the value 20 to the variable y using the <- operator.
Show hint
Write: x <- 10 and on the next line: y <- 20
Solution available after 3 attempts
Create a vector containing the values 5, 10, 15, 20 and assign it to the variable called numbers.
Show hint
Use the c() function like this: numbers <- c(5, 10, 15, 20)
Solution available after 3 attempts
Given the vectors v1 and v2, calculate their sum and assign the result to the variable total.
Show hint
Add the two vectors directly: total <- v1 + v2
Solution available after 3 attempts
Create a sequence of numbers from 1 to 10 incremented by 2 using the seq() function and assign it to the my_seq variable.
Show hint
Use the seq() function: my_seq <- seq(from = 1, to = 10, by = 2)
Solution available after 3 attempts
Given the vector sales <- c(100, 150), assign the names 'Mon' and 'Tue' to the vector using the names() function.
Show hint
Set names(sales) <- c('Mon', 'Tue')
Solution available after 3 attempts
Concept check
What does the following vector recycling snippet print to the console?
x <- c(10, 20, 30, 40)
y <- c(1, 2)
x + yGiven nums <- c(10, 20, 30, 40), what expression returns c(10, 30, 40) excluding the second element?