R Vector Operations
Math on Vectors
In many programming languages, you need a loop to change every item in a list.
In R, math works on the whole vector at once. This is one of the things that makes R so good for working with data:
Example
prices <- c(10, 20, 30)
prices * 2
prices + 5
Try it Yourself »
Every item is multiplied by 2, and then 5 is added to every item.
If you use two vectors of the same length, R works item by item. The first items are added together, then the second items, and so on:
Example
a <- c(1, 2, 3)
b <- c(10, 20, 30)
a + b
Try it Yourself »
Functions on Vectors
Many functions work on all the items in a vector. For example sum(), mean() (the average), min() and max():
Example
scores <- c(85, 92, 78, 90)
sum(scores)
mean(scores)
max(scores)
Try it Yourself »
Compare Vectors
A comparison also works on every item. The result is a vector of TRUE and FALSE values:
Example
scores <- c(85, 42, 78, 30)
scores > 50
Try it Yourself »
Filter a Vector
Put a condition inside the brackets [] to get only the items where the condition is TRUE:
Example
scores <- c(85, 42, 78, 30)
scores[scores > 50]
Try it Yourself »
Only 85 and 78 are greater than 50, so only they are returned.
Use which() to get the positions of the items that match, and sum() to count them (R counts each TRUE as 1):
Example
scores <- c(85, 42, 78, 30)
which(scores > 50)
sum(scores > 50)
Try it Yourself »
The ifelse() Function
The ifelse() function checks a condition for every item, and returns one value if it is TRUE, and another value if it is FALSE:
Example
scores <- c(85, 42, 78, 30)
ifelse(scores > 50, "Pass", "Fail")
Try it Yourself »