Syntax and vectors
โ Report an issue with this lessonname <- "Ada"
age <- 28
price <- 29.99
prices <- c(29.99, 59.99, 99.99, 149.99)
print(mean(prices))
print(prices * 1.1) # applies to every element at once
<- is the traditional assignment operator (=
also works). c() combines values into a vector -- R's core
data structure, and operations on it are automatically "vectorized"
across every element.
There's actually no such thing as a single scalar value in R -- even
price <- 29.99 creates a vector of length 1. This is why
every operation you do on a "single" number also works transparently on
an entire vector: R doesn't have a separate concept of scalar math versus
array math the way many languages do.
Indexing is one of the biggest differences from most other languages: R vectors are indexed starting at 1, not 0, and square brackets accept far more than a single position -- a vector of positions, a range, or even a logical (boolean) vector the same length as the data, which is how filtering is typically done:
prices <- c(29.99, 149.99, 59.99, 9.99)
prices[1] # 29.99 -- first element (not "zeroth")
prices[2:3] # elements 2 through 3
prices[-1] # every element EXCEPT the first
prices[prices > 50] # logical indexing: only elements greater than 50
prices[c(TRUE, FALSE, TRUE, FALSE)] # equivalent, spelled out manually
Recycling is another vectorization quirk worth knowing: if you combine two vectors of different lengths in an arithmetic operation, R "recycles" (repeats) the shorter one to match the longer one's length, issuing a warning if the lengths aren't a clean multiple of each other:
c(1, 2, 3, 4) + c(10, 20) # [1] 11 22 13 24 -- c(10, 20) recycled to c(10, 20, 10, 20)
This is powerful once you're used to it (no explicit loop needed to apply a two-element pattern across a longer vector) but a common source of silent bugs when the recycling wasn't actually intended -- always double-check vector lengths line up the way you expect before relying on an operation between two vectors.
Try it yourself
[1] 79.99
Run your code and get it working before marking this lesson complete.
9 more lessons โ including Capstone project: analyze a course catalog โ plus a certificate are waiting.
Unlock the full course โ $149.99