-2

I have this matrix:

mat=matrix(c(1,1,1,2,2,2,3,4,NA,
                 4,4,4,4,4,3,5,6,4,
                 3,3,5,5,6,8,0,9,NA,
                 1,1,1,1,1,4,5,6,1),nrow=4,byrow=TRUE)
    print(mat)

        #      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
        # [1,]    1    1    1    2    2    2    3    4   NA
        # [2,]    4    4    4    4    4    3    5    6    4
        # [3,]    3    3    5    5    6    8    0    9   NA
        # [4,]    1    1    1    1    1    4    5    6    1

I should replace the NA values with other values, in this way:
I have another matrix:

mat2=matrix(c(24,1,3,2, 4,4,4,4, 3,2,2,5, 1,3,5,1),nrow=4,byrow=TRUE)

     [,1] [,2] [,3] [,4]
[1,]   24    1    3    2
[2,]    4    4    4    4
[3,]    3    2    2    5
[4,]    1    3    5    1

and the subset with the index of the rows with NA of the first matrix "mat":

subset=c(1,3)

I want to replcace the NA of the matrix with the colnames of the value of the row with the max value.

in this case, I will have "1" for the first row and "4" for the third one, I don't care about row 2 and 4.

nicola
  • 83
  • 7
  • See `?max.col`, e.g. [here](http://stackoverflow.com/questions/8220343/is-there-something-like-a-pmax-index) -- `max.col(mat2[subset, ], "first")` – alexis_laz Jul 19 '16 at 17:22
  • Your `mat` is a character matrix. Use `NA` without the quotes for NA values. – Roland Jul 19 '16 at 17:24

2 Answers2

1

Use this

mat[subset,9] <- apply(mat2[subset,],1,which.max)
user2100721
  • 3,557
  • 2
  • 20
  • 29
0
mat[which(is.na(mat))] <- apply(mat2,1,max)[which(is.na(mat), arr.ind = T)[1,]]

This should replace every NA value with the maximum value from the same row in mat2. I don't have an open core to debug on so I hope this works. If you have any questions or it crashes just comment.

Adam
  • 648
  • 6
  • 18