OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in R

Code snippet on how to insert an element at the beginning of an array in R

insert <- function(arr, val){
  m <- length(arr)+1
  arr[m] <- val
  return (arr)
 }

This code uses a function to insert a given value at the beginning of an array. The function takes in a given array and a value as parameters. The first line of code creates a variable and assigns it the length of the given array plus 1. The second line assigns the value to the last element in the array. Lastly, the function returns the array now with the value inserted.

r