A vector in R is a list of items of the same data type.
To create a list of combined items forming a vector, we use the c()
function. This function only takes the list of items that make up the vector object we create.
Let’s create a vector:
# Vector of stringsmy_vector1 <- c("pear", "cherry", "lemon")# vector of numbersmy_vector2 <- c(1, 2, 3, 4, 5)# Printing the vectorsmy_vector1my_vector2
Line 2: We create a vector my_vector1
containing string values or items.
Line 5: We create another vector, my_vector2
, containing numerical values or items.
Lines 8 & 9: We print the two vectors we create.
To change the value of a vector item, we refer to their index number or position in the given vector inside brackets []
. We then assign it to a new value.
The code below shows this:
# creating a vectormy_vector <- c("pear", "cherry", "lemon")# change "pear" to applemy_vector[1] <- "apple"my_vector
my_vector.
pear
by referring to its index number or position inside a bracket [1]
. Then, we assign it to the new value we want, "apple".