Skip to main content
Statistics LibreTexts

2.7: Math with vectors

  • Page ID
    7729
  • You can apply mathematical operations to the elements of a vector just as you would with a single number:

    > my_vector <- c(4, 5, 6)
    > my_vector_times_ten <- my_vector*10
    > my_vector_times_ten
    [1] 40 50 60
    

    You can also apply mathematical operations on pairs of vectors. In this case, each matching element is used for the operation.

    > my_first_vector <- c(1,2,3)
    > my_second_vector <- c(10, 20, 20)
    > my_first_vector + my_second_vector
    [1] 11 22 23
    

    We can also apply logical operations across vectors; again, this will return a vector with the operation applied to the pairs of values at each position.

    > vector_a <- c(1,2,3)
    > vector_b <- c(1,2,4)
    > vector_a == vector_b
    [1]  TRUE  TRUE FALSE
    
    

    Most functions will work with vectors just as they would with a single number. For example, let’s say we wanted to obtain the trignometric sine for each of a set of values. We could create a vector and pass it to the sin() function, which will return as many sine values as there are input values:

    > my_angle_values <- c(0, 1, 2)
    > my_sin_values <- sin(my_angle_values)
    > my_sin_values
    [1] 0.00 0.84 0.91
    k