5.1 Simple Vector Math

One of the advantages of R is in its ability to work with vectors.

  • You can add a constant to each element of a vector.

    x <- 1:5
    2 + x
  • You can multiply each element of a vector by a constant.

    x <- 1:5
    2 * x
  • You can add two vectors together that are the same length.

    x <- c(1, 3, 5)
    y <- c(2, 4, 6)
    x + y

    Note that the elements in the same position of each vector are added together.

  • You can multiply two vectors together that are the same length.

    x <- c(1, 3, 5)
    y <- c(2, 4, 6)
    x * y

    Note that the elements in the same position of each vector are multiplied together.

  • You can raise each element of a vector to a power.

    x <- 1:5
    x^2