Reputation: 1472
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?
Upvotes: 1
Views: 400
Reputation: 887088
An option with base R
replace(example, !is.na(example), vec)
#[1] 11 NA 22 33 44 55 NA 66 77 88 99 100
Upvotes: 2
Reputation: 12559
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
Upvotes: 1
Reputation: 521103
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
Upvotes: 3