4

I have a large adjacency matrix and a dataframe with a variable 'missing'. I need to replace all rows in the matrix with NA, for which 'missing' = TRUE (rows match between matrix and dataframe).

Example: I have: matrix

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

and dataframe

  ID missing
1  1   FALSE
2  2   FALSE
3  3    TRUE

I need: matrix

     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    0    1
[3,]   NA    NA    NA

Reproducible data:

m1.data <- c(0, 1, 0, 0, 0, 1, 1, 1, 0 )
m1 <- matrix(m1.data, nrow = 3)

df <- data.frame(ID = c(1, 2, 3),
                missing = c(FALSE, FALSE, TRUE))

Hope that someone can help! Thank you so much in advance!

2 Answers 2

4

We can extract the missing column and use that as the row index in m1 and assign it to NA

m1[df$missing,] <- NA

-output

> m1
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    0    1
[3,]   NA   NA   NA

Or we may do

> NA^(df$missing) * m1
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    0    1
[3,]   NA   NA   NA
Sign up to request clarification or add additional context in comments.

3 Comments

What are you doing with ^
The NA^ changes the TRUE values to NA and FALSE to 1
@TarJae It is a hacky way i.e for ^ if you use any other value other than 0, it returns NA i.e. NA^1 NA^2, NA^0. Since, TRUE -> 1, it returns the NA
3

With which we could get the Id for the missing and assing a NA to m1 it is similar to akrun's approach m1[df$missing,] <- NA

m1[which(df$missing==TRUE),] <- NA
     [,1] [,2] [,3]
[1,]    0    0    1
[2,]    1    0    1
[3,]   NA   NA   NA

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.