To insert an item at a specific index in a vector in R, you can use the append()
function. This function allows you to append elements to a vector at a specified position.
In this example,
c()
function.append()
function to insert the integer at the desired index.# Create a vector of integers
numbers <- c(1, 2, 3, 4, 5)
# Declare an integer to insert
new_number <- 10
# Index to insert
index <- 3
# Insert the integer at the desired index
numbers <- append(numbers, new_number, after = index - 1)
# Print the updated vector
print(numbers)
[1] 1 2 10 3 4 5
In this example,
c()
function.append()
function to insert the string at the desired index.# Create a vector of strings
words <- c("apple", "banana", "orange")
# Declare a string to insert
new_word <- "grape"
# Index to insert
index <- 2
# Insert the string at the desired index
words <- append(words, new_word, after = index - 1)
# Print the updated vector
print(words)
[1] "apple" "grape" "banana" "orange"
In this tutorial, we learned How to Insert an Item at Specific Index in a Vector in R language with well detailed examples.