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

Atomic Types, Coercion and Matrices

Explore Stage

Homogeneity of atomic vectors

Understand what happens when you mix different types in a vector or matrix.

Every atomic vector in R (including a matrix) must contain elements all of the same type. If you try to mix text and numbers inside c(...), R doesn't throw an error: it automatically converts everything to the most expressive type available according to a fixed scale.

Atomic types and the coercion hierarchy

R's coercion hierarchy follows exactly this ascending order:

logical → integer → numeric (double) → character

Type RLiteral examplesVerification functionKeynotes
logicalTRUE, FALSEis.logical(x)In the calculations TRUE == 1 and FALSE == 0
integer1L, 42Lis.integer(x)The suffix L forces a 32-bit integer
numeric3.14, 10is.numeric(x)Default type in R (floating point double)
character"Alice", 'IT'is.character(x)Wins over any other type in a mix

Test the promotion rule by clicking on the atoms in the simulator below:

Example 1 — Implicit and explicit coercion

R
mixed <- c(TRUE, 10L, 2.5, "Ada")
print(mixed)
# [1] "TRUE" "10"   "2.5"  "Ada"
cat("typeof(mixed):", typeof(mixed), "\n")
# typeof(mixed): character

# Coercizione esplicita da logical a numerico (utile per contare TRUE!)
flags <- c(TRUE, FALSE, TRUE, TRUE)
cat("Active count:", sum(flags), "\n")
# Active count: 3

Categories with factor()

When a variable contains a closed set of categories (e.g. "Low", "Medium", "High", or departments "IT", "HR", "Sales"), R offers factor(). A factor internally stores integer codes linked to a list of levels.

Example 2 — Factors and level ordering

R
categories <- c("A", "B", "A", "C")
cat_factor <- factor(categories)
print(levels(cat_factor))
# [1] "A" "B" "C"
print(table(cat_factor))

Two-dimensional matrices (matrix, cbind, rbind)

A matrix is an atomic vector arranged in rows and columns. By default R fills matrices by column (byrow = FALSE): specify byrow = TRUE if you enter numbers row by row.

Access uses [riga, colonna]: leaving one side blank selects the entire row (mat[1, ]) or the entire column (mat[, 3]).

Example 3 — Construction and slicing of a matrix

R
# Riempimento predefinito per colonna (1, 2 nella col 1; 3, 4 nella col 2...)
mat <- matrix(1:6, nrow = 2, ncol = 3)
print(mat)
#      [,1] [,2] [,3]
# [1,]    1    3    5
# [2,]    2    4    6

cat("Element [1, 3]:", mat[1, 3], "\n")
# Element [1, 3]: 5

Example 4 — Combining vectors with cbind() and rbind()

You can assemble matrices by tiling vectors as columns (cbind) or stacking them as rows (rbind).

R
col1 <- c(10, 20)
col2 <- c(30, 40)

mat_cols <- cbind(col1, col2)
mat_rows <- rbind(col1, col2)

print(dim(mat_cols)) # [1] 2 2

Test yourself: guided exercises

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

Declare a logical variable called is_active set to TRUE and a character variable called user_name set to 'Alice'.

Loading editor…
Show hint

Use the <- operator for both variables on separate lines.

Solution available after 3 attempts

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

Create a matrix called mat containing values from 1 to 6, structured with 2 rows (nrow = 2) and 3 columns (ncol = 3).

Loading editor…
Show hint

Use the function matrix(1:6, nrow = 2, ncol = 3)

Solution available after 3 attempts

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

Given the mat matrix already created, extract the element positioned in the first row and third column, and save it in the val variable.

Loading editor…
Show hint

Access the element using square brackets: val <- mat[1, 3]

Solution available after 3 attempts

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

Create a factor from the categories vector and assign it to the cat_factor variable.

Loading editor…
Show hint

Use the factor() function: cat_factor <- factor(categories)

Solution available after 3 attempts

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

Given the vectors col1 and col2, combine them as columns of a matrix using cbind() and assign the result to my_matrix.

Loading editor…
Show hint

Use: my_matrix <- cbind(col1, col2)

Solution available after 3 attempts

Concept check

R Quiz#r.m1.l2.e6
Ready

What does typeof(c(TRUE, 5L, 2.5, '99')) return?

R
v <- c(TRUE, 5L, 2.5, "99")
typeof(v)
Answer options
R Quiz#r.m1.l2.e7
Ready

How is the 1:6 vector arranged in matrix(1:6, nrow = 2, ncol = 3) without additional arguments?

Answer options