Home > Software design >  How to add "NA" into a vector where the positions are specifically identified?
How to add "NA" into a vector where the positions are specifically identified?

Time:09-09

Suppose we have a vector:

x<-c(1,3,4,6,7)

And we have another vector that specifies the positions of NAs:

NAs<-c(2,5)

How can I add NA to the vector x in the 2nd and 5th index so x becomes

x
1 NA 3 4 NA 6 7

Thanks!

CodePudding user response:

Do you want this?

> replace(sort(c(x, NAs)), NAs, NA)
[1]  1 NA  3  4 NA  6  7

or a safer solution

> v <- c(x, NAs)

> replace(rep(NA, length(v)), !seq_along(v) %in% NAs, x)
[1]  1 NA  3  4 NA  6  7

CodePudding user response:

With a for loop, using append:

for (i in sort(NAs)) x <- append(x, NA, after = i - 1)
#[1]  1 NA  3  4 NA  6  7
  • Related