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 strings my_vector1 <- c("pear", "cherry", "lemon") # vector of numbers my_vector2 <- c(1, 2, 3, 4, 5) # Printing the vectors my_vector1 my_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 vector my_vector <- c("pear", "cherry", "lemon") # change "pear" to apple my_vector <- "apple" my_vector
pearby referring to its index number or position inside a bracket
. Then, we assign it to the new value we want,
View all Courses