user32416 user32416 - 2 months ago 14
R Question

Uncover values of one data frame with another mask data frame

Suppose I have two data frames

A
and
B_mask
, where

A <- as.data.frame( matrix(1:20,nrow=4) )

V1 V2 V3 V4 V5
1 1 5 9 13 17
2 2 6 10 14 18
3 3 7 11 15 19
4 4 8 12 16 20


And suppose also,

B_mask <- matrix(FALSE, nrow=4, ncol=5)
B_mask[2:3, 1:3] <- TRUE
B_mask <- as.data.frame(B_mask)

V1 V2 V3 V4 V5
1 FALSE FALSE FALSE FALSE FALSE
2 TRUE TRUE TRUE FALSE FALSE
3 TRUE TRUE TRUE FALSE FALSE
4 FALSE FALSE FALSE FALSE FALSE


How does one get a
result
data frame such that:


  • If an entry in
    B_mask
    is equal to
    TRUE
    , uncover the corresponding value in
    A
    ? For example, because
    B_mask[2,1] = TRUE
    , I would want
    result[2,1] = A[2,1] = 2
    .

  • If an entry in
    B_mask
    is equal to
    FALSE
    , cover the corresponding value in
    A
    as
    NA
    ? For example, because
    B_mask[3,4] = FALSE
    , I would want
    result[3,4] = NA
    .



Thanks!

Answer

We create a copy of the dataset ('res'), convert the 'FALSE' to NA in 'B_mask', and use the logical index to subset the corresponding values of 'A' and assign the output back to 'res' with the structure intact ([])

res <- A
res[] <- as.matrix(A)[as.logical(NA^!B_mask)]

Or as @alexis_laz mentioned this can also done with

is.na(res) <- !as.matrix(B_mask)