To insert an element at a specific index in a list in R, you can use the insert
function from the magrittr
package or manipulate list indices directly.
In this example,
numbers
with initial integer values.insert
function from the magrittr
package to insert a new element at the desired index.library(magrittr)
numbers <- c(1, 2, 3, 4, 5)
numbers <- insert(numbers, 3, 10)
print(numbers)
[1] 1 2 10 3 4 5
In this example,
numbers
with initial integer values.numbers <- c(1, 2, 3, 4, 5)
index <- 3
element <- 10
updated_list <- c(numbers[1:(index-1)], element, numbers[index:length(numbers)])
print(updated_list)
[1] 1 2 10 3 4 5
In this tutorial, we learned How to Insert an Element at Specific Index in a List in R language with well detailed examples.