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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With