Home > Back-end >  How would you print out the values exceeding the vector and replace them with NA in R?
How would you print out the values exceeding the vector and replace them with NA in R?

Time:03-23

I'm supposed to make a function where you can insert a value into a vector, but if you attempt to place the value outside of the vector it gives the following output enter image description here

This is what I have done so far which works for values within the dimensions of the vector, but I cannot figure out how to get the output from the image above

a <- 1:10
insert <- function(x, where, what) {
 if(where<x 1) {
append(x,what,where - 1)}
  else{
print("Warning message")  
  }
}

CodePudding user response:

If where exceeds the length of x, we can append NA to x. You can use warning() to display warning messages.

I've also changed your if statement to include length(), because we are comparing the length of x with your where argument.

insert <- function(x, where, what) {
  if (where < length(x)   1) {
    append(x,what,where - 1)
  } else{
    warning(paste(where, "exceeds the dimension of the vector"))
    append(c(x, rep(NA, where - length(x) - 1)), what, where - 1)
  }
}

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