bluepole bluepole - 1 month ago 19
R Question

Replace the elements in a matrix with NA for those with row and column names not stored in a dataframe

Suppose I have a matrix

rmatrix
defined below:

set.seed(10)
rmatrix <- matrix(sample(0:100, 16), ncol=4)
dimnames(rmatrix) <- list(rownames(rmatrix, do.NULL = FALSE,
prefix = "row"), colnames(rmatrix, do.NULL = FALSE, prefix = "col"))
rmatrix

col1 col2 col3 col4
row1 51 8 57 10
row2 30 21 39 52
row3 42 26 59 31
row4 67 25 100 36


A dataframe
df
stores some combinations of the row and column names of
rmatrix
:

df <- data.frame(r = c('row1', 'row1', 'row3', 'row4', 'row4', 'row4'),
c = c('col2', 'col4', 'col3', 'col3', 'col1', 'col2'))
df
r c
1 row1 col2
2 row1 col4
3 row3 col3
4 row4 col3
5 row4 col1
6 row4 col2


How to change any element in
rmatrix
to
NA
if its names are not in
df
? Thanks!

d.b d.b
Answer Source
out = replace(rmatrix*NA, as.matrix(df), rmatrix[as.matrix(df)])
out
#     col1 col2 col3 col4
#row1   NA    8   NA   10
#row2   NA   NA   NA   NA
#row3   NA   NA   59   NA
#row4   67   25  100   NA

The following would work even when rmatrix is made of characters

replace(replace(rmatrix, TRUE, NA), as.matrix(df), rmatrix[as.matrix(df)])