Skip to main content
Statistics LibreTexts

2.6: Vectors

  • Page ID
    7728
  • You may have noticed that the my_random_numbers created above wasn’t like the variables that we had seen before — it contained a number of values in it. We refer to this kind of variable as a vector.

    If you want to create your own new vector, you can do that using the c() function:

    > my_vector <- c(4, 5, 6)
    > my_vector
    [1] 4 5 6
    

    You can access the individual elements within a vector by using square brackets along with a number that refers to the location within the vector. These index values start at 1, which is different from many other programming languages that start at zero. Let’s say we want to see the value in the second place of the vector:

    > my_vector[2]
    [1] 5
    

    You can also look at a range of positions, by putting the start and end locations with a colon in between:

    > my_vector[2:3]
    [1] 5 6
    

    You can also change the values of specific locations using the same indexing:

    > my_vector[3] <- 7
    > my_vector
    [1] 4 5 7