Vectors
Create vectors with c(), : and seq(), calculate on a whole vector at once, and pick elements by position or condition.
Runs in Zerethon IDE · R 4.5
Official R documentation ↗
The vector is R's basic data type: even a single number is a vector of length 1. Arithmetic and comparisons work on every element at once, so many loops in other languages are one expression in R.
main.R
scores <- c(70, 95, 82, 60)
print(scores * 2)
print(scores[scores > 75])
print(mean(scores))
print(sort(scores, decreasing = TRUE)[1:2])
print(length(scores))
print(seq(1, 10, by = 3))
print(1:5 + 10)
print(which(scores == max(scores)))
print(scores[-1])
print(rep(c("a", "b"), times = 2))
Output
[1] 140 190 164 120 [1] 95 82 [1] 76.75 [1] 95 82 [1] 4 [1] 1 4 7 10 [1] 11 12 13 14 15 [1] 2 [1] 95 82 60 [1] "a" "b" "a" "b"
- Indexes start at 1.
x[-1]means “all but the first”, not the last element. x[x > 75]keeps the elements where the condition isTRUE.- A vector holds one type:
c(1, "a")turns the number into text. - Combining vectors of different lengths recycles the shorter one, which is easy to miss.