I have a deep nested data and a function that runs on it through purrr. Here is a mock data & analysis that resembles my case:
df <- tibble::tribble(
~A, ~B, ~C,
"e", 2L, 6L,
"e", 5L, 8L,
"e", 5L, 3L,
"f", 3L, 8L,
"f", 4L, 1L,
"f", 5L, 6L,
"g", 3L, 9L,
"g", 4L, 2L,
"g", 5L, 7L,
"h", 5L, 4L
)
I need to filter different variables based on different conditions. I need to do something like this:
df1 <- df %>% group_by(A) %>%
nest() %>%
case_when(A == "e" ~filter(B<4),
A == "f" ~filter(C<=6),
A == "g" ~filter(B<5, C<7))
My desired output should be:
desired_output <- tibble::tribble(
~A, ~B, ~C,
"e", 2L, 6L,
"f", 4L, 1L,
"f", 5L, 6L,
"g", 4L, 2L
)
We can do the following to filter for different conditions.
library(tidyverse)
df %>%
filter((A %in% "e" & B < 4) |
(A %in% "f" & C <= 6) |
(A %in% "g" & B < 5 & C < 7))
# # A tibble: 4 x 3
# A B C
# <chr> <int> <int>
# 1 e 2 6
# 2 f 4 1
# 3 f 5 6
# 4 g 4 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With