Write a Function to Insert a Value at a Given Position in a Vector

Write a Function to Insert a Value at a Given Position in a Vector

I'm looking to write a function named insert(x, where, what) that inserts a value (what) at a given position (where) in a vector (x)

If the given position exceeds the dimension of a vector there should be a warning message that prints out and the positions between the last element of the vector and the inserted value should be filled with NAs

This is what I have so far but it results in a vertical vector:

    x <- 1:10
insert <- function (x, where, what)
  {if (where>10) c(append(x, what, after = where-1),print("Warning message: In insert(a, 11 , 0) : 11 exceeds the dimensions of the vector"))
  else
    append(x, what, after = where-1)}


insert(x, 5, 0)
insert(x, 11, 0)
insert(x,15,0)

Below is the desired output:

    a <- 1:10

insert(a, 5, 0) 
[1] 1 2 3 4 0 5 6 7 8 9 10

insert(a, 11, 0) 
[1] 1 2 3 4 5 6 7 8 9 10 0 
Warning message: 
In insert(a, 11, 0) : 11 exceeds the dimension of the vector

insert(a, 15, 0) 
[1] 1 2 3 4 5 6 7 8 9 10 NA NA NA NA 0 
Warning message: 
In insert(a, 15, 0) : 15 exceeds the dimension of the vector

1 Answer

One approach to achieve your desired result may look like so:

insert <- function(x, where, what) {
  lenx <- length(x)
  if (where > lenx) {
    warning(paste0(where, " exceeds the dimensions of the vector."))
    res <- c(x, rep(NA, where - lenx - 1), what)
  } else {
    res <- c(x[seq(where - 1)], what, x[seq(where, lenx)])
  }
  return(res)
}

x <- 1:10

insert(x, 5, 0)
#>  [1]  1  2  3  4  0  5  6  7  8  9 10
insert(x, 11, 0)
#> Warning in insert(x, 11, 0): 11 exceeds the dimensions of the vector.
#>  [1]  1  2  3  4  5  6  7  8  9 10  0
insert(x, 15, 0)
#> Warning in insert(x, 15, 0): 15 exceeds the dimensions of the vector.
#>  [1]  1  2  3  4  5  6  7  8  9 10 NA NA NA NA  0
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.