0
0
R Programmingprogramming~5 mins

Modifying and adding elements in R Programming

Choose your learning style9 modes available
Introduction

We change or add elements in data to update or grow our information. This helps keep data correct and useful.

You want to fix a wrong value in a list or vector.
You need to add a new item to your data collection.
You want to update a specific part of your data based on a condition.
You are building a list step-by-step by adding elements.
You want to replace old data with new data in your program.
Syntax
R Programming
vector[index] <- new_value
vector <- c(vector, new_value)

Use square brackets [ ] to select the element you want to change.

Use the c() function to add new elements to a vector.

Examples
This changes the second element from 20 to 25.
R Programming
x <- c(10, 20, 30)
x[2] <- 25
This adds a new element 40 at the end of the vector.
R Programming
x <- c(10, 20, 30)
x <- c(x, 40)
This increases the first element by 10, changing 5 to 15.
R Programming
x <- c(5, 15, 25)
x[1] <- x[1] + 10
Sample Program

We start with a vector of three numbers. Then we change the second number to 20. Next, we add 40 to the end. Finally, we print the updated vector.

R Programming
numbers <- c(1, 2, 3)
numbers[2] <- 20
numbers <- c(numbers, 40)
print(numbers)
OutputSuccess
Important Notes

Remember R vectors start at index 1, not 0 like some other languages.

Adding elements with c() creates a new vector; it does not change the original in place.

Summary

You can change elements by using their position with [ ] and assigning a new value.

To add elements, use the c() function to combine old and new values.

These simple steps help keep your data accurate and complete.