2

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!

Maël
  • 45,206
  • 3
  • 29
  • 67
  • Related: [Insert elements into a vector at particular indexes](https://stackoverflow.com/questions/1493969/insert-elements-into-a-vector-at-particular-indexes) – Henrik Sep 08 '22 at 12:51

2 Answers2

3

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
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
2

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
Maël
  • 45,206
  • 3
  • 29
  • 67