OneBite.Dev - Coding blog in a bite size

insert an element at a specific index in an array in R

Code snippet on how to insert an element at a specific index in an array in R

  arr <- c("a", "b", "c", "d", "e")
  insert_index <- 3
  new_elem <- "x"  
  arr[insert_index] <- new_elem

This code assigns an array with 5 elements to the variable arr. Then it sets the index at which to insert a new element, insert_index, to 3. Lastly, it assigns the new element to be inserted, new_elem, to the letter “x”. Once all the variables are assigned, the code replaces the element at the index 3 of the array with the new element, “x”. The resulting array will now be (a, b, x, d, e).

r