Skip to main content
Module 1 · Lesson 1 of 21/18 in the course~18 min
Module lessons (1/2)

Variables, Vectors and Recycling

Warm-Up Stage

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

R
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.4

Vectors, 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 / SyntaxMain purposeExample in RResult
c(a, b, c)Combine values into a vectorc(10, 20, 30)10 20 30
1:5Whole sequence at step 13:63 4 5 6
seq(from, to, by)Sequence with customized stepseq(0, 10, by = 5)0 5 10
rep(val, times)Repeats a value or vectorrep(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 elementc(10, 20, 30)[-2]10 30

Example 2 — Creation, positive slicing and negative indices

R
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 195

Vectorized 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 4 combined with 1 or 2 (exact multiple, no warning).
  • Unbalanced recycling: length 5 combined with 2 or 3 still 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

R
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 320

Example 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.

R
revenue <- c(1200, 1450, 980)
names(revenue) <- c("Jan", "Feb", "Mar")

print(revenue["Feb"])
# Feb
# 1450

Test yourself: guided exercises

Exercise#r.m1.l1.e1
Attempts: 0Loading…

Assign the value 10 to the variable x and the value 20 to the variable y using the <- operator.

Loading editor…
Show hint

Write: x <- 10 and on the next line: y <- 20

Solution available after 3 attempts

Exercise#r.m1.l1.e2
Attempts: 0Loading…

Create a vector containing the values 5, 10, 15, 20 and assign it to the variable called numbers.

Loading editor…
Show hint

Use the c() function like this: numbers <- c(5, 10, 15, 20)

Solution available after 3 attempts

Exercise#r.m1.l1.e3
Attempts: 0Loading…

Given the vectors v1 and v2, calculate their sum and assign the result to the variable total.

Loading editor…
Show hint

Add the two vectors directly: total <- v1 + v2

Solution available after 3 attempts

Exercise#r.m1.l1.e4
Attempts: 0Loading…

Create a sequence of numbers from 1 to 10 incremented by 2 using the seq() function and assign it to the my_seq variable.

Loading editor…
Show hint

Use the seq() function: my_seq <- seq(from = 1, to = 10, by = 2)

Solution available after 3 attempts

Exercise#r.m1.l1.e5
Attempts: 0Loading…

Given the vector sales <- c(100, 150), assign the names 'Mon' and 'Tue' to the vector using the names() function.

Loading editor…
Show hint

Set names(sales) <- c('Mon', 'Tue')

Solution available after 3 attempts

Concept check

R Quiz#r.m1.l1.e6
Ready

What does the following vector recycling snippet print to the console?

R
x <- c(10, 20, 30, 40)
y <- c(1, 2)
x + y
Answer options
R Quiz#r.m1.l1.e7
Ready

Given nums <- c(10, 20, 30, 40), what expression returns c(10, 30, 40) excluding the second element?

Answer options