R Vectors
A vector is an ordered sequence of values of the same type. It is R's most fundamental data structure: even a single number is a vector of length 1. Create vectors with c() ("combine"):
r · try it yourself
heights <- c(1.62, 1.75, 1.80, 1.68)
names_v <- c("Ana", "Ben", "Cai", "Dee")
heights
names_v
length(heights)[1] 1.62 1.75 1.80 1.68
[1] "Ana" "Ben" "Cai" "Dee"
[1] 4
Creating sequences
| Code | Result |
|---|---|
1:5 |
1 2 3 4 5 |
seq(2, 10, by = 2) |
2 4 6 8 10 |
seq(0, 1, length.out = 5) |
0 0.25 0.5 0.75 1 |
rep("x", 3) |
"x" "x" "x" |
rep(1:2, times = 3) |
1 2 1 2 1 2 |
rep(1:2, each = 2) |
1 1 2 2 |
r · try it yourself
seq(10, 50, by = 10)
seq(1, 2, length.out = 3)
rep(c("a", "b"), times = 2)
rep(c("a", "b"), each = 2)
numeric(3)
character(2)[1] 10 20 30 40 50
[1] 1.0 1.5 2.0
[1] "a" "b" "a" "b"
[1] "a" "a" "b" "b"
[1] 0 0 0
[1] "" ""
Accessing elements
Use square brackets. Positions start at 1. You can pass a single position, a vector of positions, negative positions (to drop elements) or a logical vector:
r · try it yourself
x <- c(10, 20, 30, 40, 50)
x[1]
x[c(2, 4)]
x[-1] # everything except the first
x[2:4]
x[x > 25] # logical filter
x[length(x)] # last element[1] 10
[1] 20 40
[1] 20 30 40 50
[1] 20 30 40
[1] 30 40 50
[1] 50
Named vectors
Elements can have names, which you can then use for access:
r · try it yourself
prices <- c(apple = 0.5, bread = 2.2, milk = 1.1)
prices["bread"]
names(prices)
prices[c("milk", "apple")]bread
2.2
[1] "apple" "bread" "milk"
milk apple
1.1 0.5
Changing and adding elements
r · try it yourself
v <- c(5, 6, 7)
v[2] <- 60
v
v <- c(v, 8, 9) # append
v
v[8] <- 100 # gaps are filled with NA
v[1] 5 60 7
[1] 5 60 7 8 9
[1] 5 60 7 8 9 NA NA 100
Vectorised operations
Operations apply to every element, and two vectors of the same length combine element by element:
r · try it yourself
qty <- c(2, 1, 5)
unit_price <- c(3.5, 10, 0.8)
qty * unit_price
sum(qty * unit_price)
rev(qty)
sort(unit_price, decreasing = TRUE)
order(unit_price) # positions that would sort it[1] 7 10 4
[1] 21
[1] 5 1 2
[1] 10.0 3.5 0.8
[1] 3 1 2
Useful vector functions
| Function | Purpose |
|---|---|
length(x) |
number of elements |
sum, mean, min, max |
summaries |
sort(x), rev(x), order(x) |
ordering |
unique(x), table(x) |
distinct values, counts |
which(cond) |
positions where a condition holds |
head(x, n), tail(x, n) |
first / last n elements |
x %in% y |
membership test |
r · try it yourself
colours <- c("red", "blue", "red", "green", "blue", "red")
unique(colours)
table(colours)
which(colours == "red")
head(colours, 2)[1] "red" "blue" "green"
colours
blue green red
2 1 3
[1] 1 3 6
[1] "red" "blue"
Test yourself
What is c(4, 8, 15, 16)[-2]?
- 8
- 4 15 16
- 4 8
- 15
What does rep(1:2, each = 3) produce?
- 1 2 1 2 1 2
- 1 1 1 2 2 2
- 3 3
- 1 2 3
What is the index of the first element of an R vector?
- 0
- 1
- -1
- It depends