Module lessons (2/2)
Atomic Types, Coercion and Matrices
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 R | Literal examples | Verification function | Keynotes |
|---|---|---|---|
logical | TRUE, FALSE | is.logical(x) | In the calculations TRUE == 1 and FALSE == 0 |
integer | 1L, 42L | is.integer(x) | The suffix L forces a 32-bit integer |
numeric | 3.14, 10 | is.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
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: 3Categories 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
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
# 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]: 5Example 4 — Combining vectors with cbind() and rbind()
You can assemble matrices by tiling vectors as columns (cbind) or stacking them as rows (rbind).
col1 <- c(10, 20)
col2 <- c(30, 40)
mat_cols <- cbind(col1, col2)
mat_rows <- rbind(col1, col2)
print(dim(mat_cols)) # [1] 2 2Test yourself: guided exercises
Declare a logical variable called is_active set to TRUE and a character variable called user_name set to 'Alice'.
Show hint
Use the <- operator for both variables on separate lines.
Solution available after 3 attempts
Create a matrix called mat containing values from 1 to 6, structured with 2 rows (nrow = 2) and 3 columns (ncol = 3).
Show hint
Use the function matrix(1:6, nrow = 2, ncol = 3)
Solution available after 3 attempts
Given the mat matrix already created, extract the element positioned in the first row and third column, and save it in the val variable.
Show hint
Access the element using square brackets: val <- mat[1, 3]
Solution available after 3 attempts
Create a factor from the categories vector and assign it to the cat_factor variable.
Show hint
Use the factor() function: cat_factor <- factor(categories)
Solution available after 3 attempts
Given the vectors col1 and col2, combine them as columns of a matrix using cbind() and assign the result to my_matrix.
Show hint
Use: my_matrix <- cbind(col1, col2)
Solution available after 3 attempts
Concept check
What does typeof(c(TRUE, 5L, 2.5, '99')) return?
v <- c(TRUE, 5L, 2.5, "99")
typeof(v)How is the 1:6 vector arranged in matrix(1:6, nrow = 2, ncol = 3) without additional arguments?