1

annoying little problem, where I can't add multiple NAs to vector on predetermined places.

I have example vector from which I can determine missing value places.

example <- c(1, NA, 2, 3, 4, 5, NA, 6, 7, 8, 9, 10)

missing_spots <- which(is.na(example))

Now I have random vector, where I need to add NAs to correct spots.

vec <- c(11, 22, 33, 44, 55, 66, 77, 88, 99, 100)

Append function won't take multiple after values.

append(vec, NA, missing_spots - 1)

only thing I have found is piping appends, but my data is too complicated to know how many times append should be used.

append(vec, NA, missing_spots[1]-1) %>% 
  append(., NA, missing_spots[2]-1)

 [1]  11  NA  22  33  44  55  NA  66  77  88  99 100

How do I get full proof method to add NAs to correct spots?

Sotos
  • 51,121
  • 6
  • 32
  • 66
Hakki
  • 1,440
  • 12
  • 26
  • https://stackoverflow.com/questions/18951248/insert-elements-in-a-vector-in-r take a look at this – boski Aug 06 '19 at 13:01

3 Answers3

3

One simple option here would be to use example as a template, and assign all non NA values to the vec replacement vector:

example <- c(1, NA, 2, 3, 4, 5, NA, 6, 7, 8, 9, 10)
vec <- c(11, 22, 33, 44, 55, 66, 77, 88, 99, 100)
example[!is.na(example)] <- vec
example

[1]  11  NA  22  33  44  55  NA  66  77  88  99 100
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Very nice! And here I was making vectors the same length, trying to custom order it :D – Sotos Aug 06 '19 at 13:07
  • hehehe...well, we both have the same net worth *As of February 2018, he had a net worth of $8 billion* o_O – Sotos Aug 06 '19 at 13:11
2

An option with base R

replace(example, !is.na(example), vec)
#[1]  11  NA  22  33  44  55  NA  66  77  88  99 100
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can do:

example <- c(1, NA, 2, 3, 4, 5, NA, 6, 7, 8, 9, 10)
missing_spots <- which(is.na(example))
vec <- c(11, 22, 33, 44, 55, 66, 77, 88, 99, 100)

for (i in missing_spots) vec <- c(head(vec, i-1), NA, tail(vec, -(i-1)))
vec
jogo
  • 12,469
  • 11
  • 37
  • 42