Supporting Statistical Analysis for Research
1.9 Vectorized functions
An R vector is a column of values. Each of the values of a vector have to be of the same type, number, character, etc. The values of a vector can be access based on the order of the values.
Many R functions parameters are vectors. Similarly, many operators operate on vectors. These functions and operators work on all the values of a column together. There are two common types of vector operations, transforming and aggregating. Aggregating is also know as summarizing.
Examples
Math with vectors
Adding two vectors is a transforming operation. The values of the two vectors are added element by element.
vec1 <- c(7, 5, 3, 1) vec2 <- c(1, 2, 4, 8) vec1 + vec2[1] 8 7 7 9Multiplying works similarly.
vec1 * vec2[1] 7 10 12 8Aggregating functions
The sum()` function adds all the values of a vector together.
sum(vec1)[1] 16sum(vec2)[1] 15sum(vec1 * vec2)[1] 37sum(vec1, vec2)[1] 31Some other aggregating functions are,
mean(),sd(), andmedian()mean(vec1)[1] 4median(vec2)[1] 3mean(vec1 * vec2)[1] 9.25sd(c(vec1, vec2))[1] 2.642374