Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-inserting NAs into a vector

Tags:

r

vector

I have a vector of values which include NAs. The values need to be processed by an external program that can't handle NAs, so they are stripped out, its written to a file, processed, then read back in, resulting in a vector of the length of the number of non-NAs. Example, suppose the input is 7 3 4 NA 5 4 6 NA 1 NA, then the output would just be 7 values. What I need to do is re-insert the NAs in position.

So, given two vectors X and Y:

 > X
 [1]  64   1   9 100  16  NA  25  NA   4  49  36  NA  81
 > Y
 [1]  8  1  3 10  4  5  2  7  6  9

produce:

8 1 3 10 4 NA 5 NA 2 7 6 NA 9

(you may notice that X is Y^2, thats just for an example).

I could knock out a function to do this but I wonder if there's any nice tricksy ways of doing it... split, list, length... hmmm...

like image 268
Spacedman Avatar asked Oct 11 '10 18:10

Spacedman


People also ask

How do I replace NAS in R?

You can replace NA values with zero(0) on numeric columns of R data frame by using is.na() , replace() , imputeTS::replace() , dplyr::coalesce() , dplyr::mutate_at() , dplyr::mutate_if() , and tidyr::replace_na() functions.

Should I replace NA with 0?

However, if we have NA values due to item nonresponse, we should never replace these missing values by a fixed number, i.e. 0.

How do you get rid of Na in a vector?

We can remove those NA values from the vector by using is.na(). is.na() is used to get the na values based on the vector index. ! is.na() will get the values except na.

How do I assign a 0 to a NA in R?

To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.


3 Answers

na.omit keeps an attribute of the locations of the NA in the original series, so you could use that to know where to put the missing values:

Y <- sqrt(na.omit(X))
Z <- rep(NA,length(Y)+length(attr(Y,"na.action")))
Z[-attr(Y,"na.action")] <- Y
#> Z
# [1]  8  1  3 10  4 NA  5 NA  2  7  6 NA  9
like image 140
Joshua Ulrich Avatar answered Sep 22 '22 19:09

Joshua Ulrich


Answering my own question is probably very bad form, but I think this is probably about the neatest:

rena <- function(X,Z){
Y=rep(NA,length(X))
Y[!is.na(X)]=Z    
Y
}
like image 33
Spacedman Avatar answered Sep 22 '22 19:09

Spacedman


Can also try replace:

replace(X, !is.na(X), Y)
like image 24
Charles Avatar answered Sep 21 '22 19:09

Charles