Apply boolean dataframe to another data frame in R

I have a data frame as such:

| x | y |
|---|---|
| a | e |
| b | f |
| c | g |
| d | h |  

and I have a dataframe of bool values ​​as such:

| x     | y     |
|-------|-------|
| FALSE | TRUE  |
| FALSE | TRUE  |
| TRUE  | FALSE |
| TRUE  | FALSE |

(in fact, this material appeared as a result of another message , but this is not very important, because this is a separate issue)

I'm just looking for a way to apply df with bool values ​​to "regular" df and get the following:

| x | y |
|---|---|
|   | e |
|   | f |
| c |   |
| d |   |

This question asked a very similar question, but the solutions diverged in different directions.

I have tried many different indexing schemes, but all of them do not preserve the rectangular structure of the result that I want.

df[mask] was too good to be true.

Any advice is greatly appreciated.

My details:

df <- data.frame(
  x = c('a', 'b', 'c', 'd'),
  y = c('e', 'f', 'g', 'h'), stringsAsFactors = F
)

mask <- structure(list(x = c(FALSE, FALSE, TRUE, TRUE), y = c(TRUE, TRUE, 
FALSE, FALSE)), .Names = c("x", "y"), row.names = c(NA, -4L), class = "data.frame")
+4
3

( @thelatemail )

df[!mask] <- ""
#   x y
# 1   e
# 2   f
# 3 c  
# 4 d 

, ! mask ( as.matrix())

str(mask)
# 'data.frame': 4 obs. of  2 variables:
#   $ x: logi  FALSE FALSE TRUE TRUE
#   $ y: logi  TRUE TRUE FALSE FALSE

str(!mask)
# logi [1:4, 1:2] TRUE TRUE FALSE FALSE FALSE FALSE ...
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:2] "x" "y"

## and
class(!mask)
# "matrix"

ifelse

df$x <- ifelse(mask$x, df$x, "")
df$y <- ifelse(mask$y, df$y, "")
+7

mapply, mask:

as.data.frame( mapply(function(x,y) ifelse(y, x, ''), df, mask))
##   x y
## 1   e
## 2   f
## 3 c  
## 4 d  
+6

We can use replace

replace(df, !mask, "")
#  x y
#1   e
#2   f
#3 c  
#4 d  
+3
source

Source: https://habr.com/ru/post/1667197/


All Articles