R Vector Functions
A vector function takes a whole vector and returns a summary of it. Most summaries are a single number.
Counting and adding
length counts the items in the vector. sum then adds those items into one total.
w <- c(4, 8, 15, 16)
print(length(w))
print(sum(w))Averaging
mean adds the three values and divides by the count. The result is one average value.
print(mean(c(1, 2, 4)))The two ends
min finds the smallest item and max finds the largest item. range returns both ends together.
w <- c(4, 8, 15, 16)
print(min(w))
print(max(w))
print(range(w))Dropping repeats
The first print shows the vector with its repeats. unique then returns each value only once.
r <- c(7, 3, 7, 5, 3)
print(r)
print(unique(r))Example
marks <- c(12, 7, 19, 7)
print(length(marks))
print(sum(marks))
print(mean(marks))
print(range(marks))Key points
- length counts the items in a vector.
- sum adds all the items together.
- mean returns the average of the items.
- min returns the smallest item.
- max returns the largest item.
- range returns the smallest and largest items as a two value vector.
- unique returns the items with repeats removed.
In this example, four marks are summarised in four calls. The total is 45 and the average is 11.25. The range shows the lowest and highest marks.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does mean(c(1, 2, 4)) print?