Skip to content
AgileLogics
5 min read

Working with Vectors

Prerequisites: Vectors

R has many built-in functions for summarizing and reshaping vectors.

Example

scores <- c(72, 95, 88, 64, 88)

sum(scores)
mean(scores)
median(scores)
min(scores)
max(scores)
range(scores)
sort(scores)
sort(scores, decreasing = TRUE)
rev(scores)
unique(scores)
which(scores > 80)
which.max(scores)
cumsum(c(1, 2, 3, 4))

Expected output

[1] 407
[1] 81.4
[1] 88
[1] 64
[1] 95
[1] 64 95
[1] 64 72 88 88 95
[1] 95 88 88 72 64
[1] 88 64 88 95 72
[1] 72 95 88 64
[1] 2 3 5
[1] 2
[1]  1  3  6 10
  • which() returns the positions where a condition is true.
  • which.max() gives the position of the largest value.
  • cumsum() gives running totals.

Named vectors

Vector elements can have names, which makes lookups readable:

ages <- c(ada = 36, linus = 28, grace = 45)
ages
ages["grace"]
names(ages)
  ada linus grace
   36    28    45
grace
   45
[1] "ada"   "linus" "grace"

Adding elements

fruits <- c("apple", "banana")
fruits <- c(fruits, "cherry")
fruits
"banana" %in% fruits
[1] "apple"  "banana" "cherry"
[1] TRUE

%in% checks whether values appear in a vector.

Practice

Given scores <- c(72, 95, 88, 95, 60), print the highest score, the average rounded to one decimal, and the positions of the scores below 75.

Show solution
scores <- c(72, 95, 88, 95, 60)
max(scores)
round(mean(scores), 1)
which(scores < 75)
[1] 95
[1] 82
[1] 1 5