Home > Net >  Specifying several separate filter conditions and run code for each of the conditions
Specifying several separate filter conditions and run code for each of the conditions

Time:03-12

In my analysis I want to cut and slice my data in several different ways (i.e. want to apply different filters), but otherwise run the same follow-up code (here count) and then ideally glue this together. So what I would do is:

df <- data.frame(x = c(1, 1, 2, 2, 3, 3),
                 y = c(1, 2, 3, 3, 2, 1),
                 z = c(1, 1, 0, 1, 0, 1))

r1 <- df %>%
  filter(x < 3 & y == 3) %>%
  count(z)

r2 <- df %>%
  filter(x != 2 & y == 1) %>%
  count(z)

full_join(r1, r2, by = "z")

which gives:

  z n.x n.y
1 0   1  NA
2 1   1   2

Now, I have a lot of different filter variants, so I'm wondering if there is an easier (tidy) way to achieve this. My idea was that I somehow provide my filter conditions as an input and then apply these filter conditions to my data frame and the bind together the results. I guess this might be able with some purrr magic, but no idea how. Anyone?

CodePudding user response:

Depends in what format do you have your filters, for example you could use eval parse:

filters <- c(
  "x < 3 & y == 3",
  "x != 2 & y == 1"
)

filters %>%
  map(~filter(df, eval(parse(text = .x))) %>% count(z)) %>%
  reduce(full_join, by = "z")

CodePudding user response:

I'm an idiot. I just realized that I could simply do:

df |>
  group_by(z) |> 
  summarize(x = sum(x < 3 & y == 3),
            y = sum(x != 2 & y == 1))
  • Related