Skip to content


[R] How to replace NAs with a specific value (in a matrix or other)

For some reason, the more basic the action I want to do in R, the harder it seems to me… So, here’s how to replace NA values with any value so that I don’t have to look for this again.

First, the easy one: in a vector:

arff=1:10;
arff[3]=NA;
arff[which(is.na(arff))]=-1;
arff;
 [1]  1  2 -1  4  5  6  7  8  9 1

In a matrix, oddly enough the syntax… is exactly the same!

arff=matrix(0,4,3);
arff[2,3]=NA;
arff[which(is.na(arff))]=5;
arff;
     [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    5
[3,]    0    0    0
[4,]    0    0    0

Actually, not that odd if you consider the matrix as a 2D array the way it’s built in C++ or such. Still, that came as a surprise to me.

Now in a data frame:

pcr=matrix(0,4,3);
pcr[2,3]=NA;
pcr=data.frame(pcr);
pcr=replace(pcr,is.na(pcr),5);
pcr;
  X1 X2 X3
1  0  0  0
2  0  0  5
3  0  0  0
4  0  0  0

Actually, replace() works on matrices and vectors too 😉

Main source: R help – How to replace all values in a data.frame with another (not 0) value

Posted in R (R-project).


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA