How to change the value of a vector item in R
Overview
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
Code explanation
-
Line 2: We create a vector
my_vector1containing 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.
Changing the value of vector items
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:
Code example
# creating a vectormy_vector <- c("pear", "cherry", "lemon")# change "pear" to applemy_vector[1] <- "apple"my_vector
Code explanation
- Line 2: We create a vector,
my_vector. - Line 5: We change the item
pearby referring to its index number or position inside a bracket[1]. Then, we assign it to the new value we want,"apple". - Line 7: We print the modified vector.