replace() Function in detail
The replace() function in R is used to replace specific values in a given vector at specified indices with new values.
Syntax:
replace(x, list, values)
Parameters:
- x: The input vector.
- list: Indices where values need to be replaced.
- values: New values that will replace the existing ones at the specified indices.
Example 1:
# R program to demonstrate
# replace function
# Initializing a vector
data <- c("Apple", "Banana", "Cherry")
# Display the original vector
data
# Replace the element at index 2 with "Blueberry"
updated_data <- replace(data, 2, "Blueberry")
# Display the updated vector
updated_data
Output:
[1] "Apple" "Banana" "Cherry"
[1] "Apple" "Blueberry" "Cherry"
Example 2:
# R program to demonstrate
# replace function
# Initializing a vector
data <- c("Red", "Green", "Blue")
# Display the original vector
data
# Replace the element at index 1 with "Yellow"
# and the element at index 3 with "Orange"
updated_data <- replace(data, c(1, 3), c("Yellow", "Orange"))
# Display the updated vector
updated_data
Output:
[1] "Red" "Green" "Blue"
[1] "Yellow" "Green" "Orange"
Leave a Reply