November 11, 2026
Exercise
What is likely wrong?
library(palaeoverse) x <- tetrapods[1:3, c("collection_no", "collection_name", "lng")] y <- tetrapods[1:3, c("collection_no", "collection_name", "formation")] out <- merge(x, y, by = "collection_no") out[["collection_name"]]
Solution
out[["collection_name"]] is NULL: the columns are collection_name.x and .y.
out[["collection_name"]]
NULL
collection_name.x
.y
- out <- merge(x, y, by = "collection_no") + out <- merge(x, y, by = c("collection_no", "collection_name"))
What could be improved?
x <- head(tetrapods$max_ma) x_updated <- c() for (i in seq_along(x)) { if (x[i] > 270) { x_updated[i] <- x[i] * 0.9 } else { x_updated[i] <- x[i] } }
Prefer vectorised code to for loops:
for
x_updated <- ifelse(x > 270, x * 0.9, x)
What could go wrong?
x <- head(tetrapods$min_ma, 3) idx_to_remove <- x[x < 0] x[-idx_to_remove]
No negative values: idx_to_remove is empty, so x[-idx_to_remove] returns numeric(0).
idx_to_remove
x[-idx_to_remove]
numeric(0)
if (length(idx_to_remove) > 0) { x[-idx_to_remove] }
Demo time!