Replace NA's with a vector

835 views Asked by At

I have a matrix 16 columns 366 rows and I want to replace the NA with the value of a vector length 16.

All the time I am getting this error:

for (i in 1:16) {
  for (j in 1:366) {
    if(is.na(ChSiz(i,j)==TRUE) {

Error: unexpected '{' in: 
"  for (j in 1:366) {
    if(is.na(ChSiz(i,j)==TRUE) {"
>        ChSiz[i,j]<-x[i]
Error in ChSiz[i, j] <- x[i] : object 'j' not found
>     }
Error: unexpected '}' in "    }"
>   }
Error: unexpected '}' in "  }"
> }
Error: unexpected '}' in "}"
1

There are 1 answers

0
David Arenburg On BEST ANSWER

From what I read, you want to replace the NAs in each column of a matrix with a corresponding value of a vector.

Lets say this is your data set and your replacement vector

set.seed(1)
(m <- matrix(sample(c(NA, 1), 25, replace = TRUE), ncol = 5))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   NA    1   NA   NA    1
# [2,]   NA    1   NA    1   NA
# [3,]    1    1    1    1    1
# [4,]    1    1   NA   NA   NA
# [5,]   NA   NA    1    1   NA
(vec <- sample(5))
## [1] 2 1 5 3 4

Here's a quite simple vectorized way to replace the NAs with corresponding values

indx <- is.na(m)
m[indx] <- vec[col(m)][indx]
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2    1    5    3    1
# [2,]    2    1    5    1    4
# [3,]    1    1    1    1    1
# [4,]    1    1    5    3    4
# [5,]    2    1    1    1    4

This is basically takes the advantage is.na returning a logical matrix that can be used as a subsetting index and the col function which converts vec to a matrix.