Menu
Coddy logo textTech

Modifying Vectors

Part of the Fundamentals section of Coddy's R journey — lesson 58 of 78.

You've learned how to create vectors and access their elements. Now let's explore how to change the values stored in a vector after it's been created.

To modify a single element, use the assignment operator with the element's index:

scores <- c(85, 92, 78, 95)
scores[2] <- 88
print(scores)

Output:

[1] 85 88 78 95

You can also modify multiple elements at once by providing a vector of positions:

temperatures <- c(70, 72, 68, 75, 71)
temperatures[c(1, 3)] <- c(69, 67)
print(temperatures)

Output:

[1] 69 72 67 75 71

To add new elements to a vector, you can assign a value to a position beyond the current length, or use c() to combine vectors:

colors <- c("red", "blue")
colors[3] <- "green"
colors <- c(colors, "yellow")
print(colors)

Output:

[1] "red"    "blue"   "green"  "yellow"
challenge icon

Challenge

Easy

You are provided with the following vector:

grades <- c(78, 85, 90, 72, 88)

Perform the following modifications in order:

  1. Change the second element to 92
  2. Change the first and fourth elements to 80 and 75 respectively (modify both at once)
  3. Add a new element 95 at position 6
  4. Use c() to append the value 82 to the end of the vector

After all modifications, print the final vector.

Your output should be:

[1] 80 92 90 75 88 95 82

Cheat sheet

To modify a single element in a vector, use the assignment operator with the element's index:

scores <- c(85, 92, 78, 95)
scores[2] <- 88
print(scores)
# Output: [1] 85 88 78 95

To modify multiple elements at once, provide a vector of positions:

temperatures <- c(70, 72, 68, 75, 71)
temperatures[c(1, 3)] <- c(69, 67)
print(temperatures)
# Output: [1] 69 72 67 75 71

To add new elements to a vector, assign a value to a position beyond the current length, or use c() to combine vectors:

colors <- c("red", "blue")
colors[3] <- "green"
colors <- c(colors, "yellow")
print(colors)
# Output: [1] "red"    "blue"   "green"  "yellow"

Try it yourself

# Initial vector
grades <- c(78, 85, 90, 72, 88)

# TODO: Write your code below
# 1. Change the second element to 92
# 2. Change the first and fourth elements to 80 and 75 respectively
# 3. Add a new element 95 at position 6
# 4. Use c() to append the value 82 to the end of the vector


# Print the final vector
print(grades)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals