Sam
Sam

Reputation: 261

Changing values in a matrix based on the column positions

I am trying to take the positions of the '1s' in the m matrix, and to use those positions to change the values in the k matrix to NA. But I am having trouble getting it after much trying.

m <- matrix(c(0, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1), 
        nrow = 4, byrow = TRUE)
m

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    1    0    1
[3,]    1    0    0    0
[4,]    0    0    1    1


k <- matrix(c(12, 32, 12, 13, 23, 31, 23, 31, 23, 32, 67,63,61, 22,99, 34), 
        nrow = 4, byrow = TRUE)
k

     [,1] [,2] [,3] [,4]
[1,]   12   32   12   13
[2,]   23   31   23   31
[3,]   23   32   67   63
[4,]   61   22   99   34

By doing the below I get the column positions of the 1s in the m matrix:

jj<- row(m)[m!=0]

[1] 3 2 4 1 2 4

I tried several approaches, but I struggle to substitute the values in the k matrix based on the row positions of the m matrix to NAs.

What I would like to achieve is the below:

     [,1] [,2] [,3] [,4]
[1,]   12   32   12   NA
[2,]   23   NA   23   NA
[3,]   NA   32   67   63
[4,]   61   22   NA   NA

Upvotes: 1

Views: 65

Answers (2)

989
989

Reputation: 12937

You could simply do this:

k[m==1] <- NA

Upvotes: 1

akrun
akrun

Reputation: 887048

We can convert to NA with

NA^(m)*k
#     [,1] [,2] [,3] [,4]
#[1,]   12   32   12   NA
#[2,]   23   NA   23   NA
#[3,]   NA   32   67   63
#[4,]   61   22   NA   NA

Or another option is

is.na(k) <- m==1

Or with replace

replace(k, m==1, NA)

Upvotes: 2

Related Questions