R / CHAPTER 01
Vectors and elementwise arithmetic
BeginnerTreat vectors as the basic unit of an R calculation.
By the end of this chapter
- Construct vectors with c
- Predict elementwise operations
- Distinguish assignment from comparison
The idea
An atomic vector contains elements of one basic type, such as logical, integer, double, or character. The c function combines values into a vector and may coerce them to a common type. A single number is also a vector of length one. Use <- to bind a name to a value, and use == when asking whether values are equal rather than assigning a new value.
Arithmetic generally acts element by element. A length-one value is recycled across a longer vector, making transformations such as adding a constant concise. Recycling longer mismatched lengths can conceal mistakes even when R permits the operation, so verify the intended dimensions. Functions such as sum combine many values into one result, while length reports how many elements are present.
scores <- c(2, 5, 8)
adjusted <- scores + 1
cat(adjusted, sep = ",")
cat("
")
cat(sum(adjusted), "
", sep = "")3,6,9 18
Adding one transforms each element independently. sum then reduces the three transformed values to a single total without changing the original scores vector.
Try it yourself
Create a vector of three temperatures, subtract their mean from each, and inspect the resulting sum.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING