2

I have the following two dataframes, the first is the main one, and the second is the logical one.

df <- data.frame(
      x= c(1:10),
      y= c(11:20),
      z= c(21:30))
> df
  x  y  z
1   1 11 21
2   2 12 22
3   3 13 23
4   4 14 24
5   5 15 25
6   6 16 26
7   7 17 27
8   8 18 28
9   9 19 29
10 10 20 30

logic_df <- data.frame(
  x = c(rep(TRUE,2),rep(FALSE,8)),
  y = c(rep(TRUE,3),rep(FALSE,7)),
  z = c(rep(FALSE,9),rep(TRUE,1))
)
    > logic_df
       x     y     z
1   TRUE  TRUE FALSE
2   TRUE  TRUE FALSE
3  FALSE  TRUE FALSE
4  FALSE FALSE FALSE
5  FALSE FALSE FALSE
6  FALSE FALSE FALSE
7  FALSE FALSE FALSE
8  FALSE FALSE FALSE
9  FALSE FALSE FALSE
10 FALSE FALSE  TRUE

my goal is to achieve this:

 x  y  z
1  1 11 21
2  2 12 22
3  3 13 23
4 10 20 30

I could achieve it by a long way so I appreciate if someone has a shortcut for it. thanks in advance

1
  • 2
    using Reduce df[Reduce('|', logic_df),] Commented Jun 21, 2022 at 7:02

3 Answers 3

4

You may try

df[rowSums(logic_df) > 0,]
    x  y  z
1   1 11 21
2   2 12 22
3   3 13 23
10 10 20 30

I'm not sure where 31 came from.

Sign up to request clarification or add additional context in comments.

Comments

3

Another possible solution, based on dplyr:

library(dplyr)

df %>% 
  filter(do.call(pmax, logic_df) == 1)

#>    x  y  z
#> 1  1 11 21
#> 2  2 12 22
#> 3  3 13 23
#> 4 10 20 30

2 Comments

Thank you, Nice hint!, I'm away from laptop now but just curious would it be the same if I wrap "rowSums(logic_df)! =0" inside the filter() as well?
Yes, @AmmarGamal, the following also works: df %>% filter(rowSums(logic_df) != 0).
0

Using if_any from dplyr

library(dplyr)
df %>%
  filter((if_any(everything(), ~ logic_df[[cur_column()]])))
   x  y  z
1  1 11 21
2  2 12 22
3  3 13 23
4 10 20 30

1 Comment

Thank you,! another question popped up, what if I want the main df to only return the matching values of TRUE while everything else is NA so that it would be of the same original size?

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.