student_R123
student_R123

Reputation: 1002

Indexing a variable by another variable in R

I have following 2 matrices.

#generate matrices    
x11=matrix(rep("green",2), 4, (2)) 
y11=matrix(c(1,0,0,1,0,0,1,1),nrow=4,byrow = T)

> x11
         [,1]    [,2]   
    [1,] "green" "green"
    [2,] "green" "green"
    [3,] "green" "green"
    [4,] "green" "green"

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

So now i need to change the value of (i,j)indexes of x11 by considering the value of y11. That means if the value of y11 is zero , then i need to change that index of x11 to red. (Ex:- I need to change the value that corresponds to first row and second column of x11 to red as the value of y11 of first row and second column is zero)

To do that i used the following code segment. But it seems to be not working.

  x11[y11] = "red"

Can anyone help me to solve this ?

Upvotes: 2

Views: 425

Answers (1)

akrun
akrun

Reputation: 887991

We can creatre a logical matrix with 'y11' i.e. !y11 return TRUE for all 0 and others as FALSE. Use that to subset the 'x11' and assign those elements to "red"

x11[!y11] <- "red"

If we don't want to change the initial matrix, then use replace

replace(x11, !y11, "red")

Upvotes: 3

Related Questions