SSCC - Social Science Computing Cooperative 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

  1. 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 9

    Multiplying works similarly.

    vec1 * vec2
    [1]  7 10 12  8
  2. Aggregating functions

    The sum()` function adds all the values of a vector together.

    sum(vec1)
    [1] 16
    sum(vec2)
    [1] 15
    sum(vec1 * vec2)
    [1] 37
    sum(vec1, vec2)
    [1] 31

    Some other aggregating functions are, mean(), sd(), and median()

    mean(vec1)
    [1] 4
    median(vec2)
    [1] 3
    mean(vec1 * vec2)
    [1] 9.25
    sd(c(vec1, vec2))
    [1] 2.642374