I have a similar problem as https://forum.posit.co/t/filter-uisng-enquos/6197,
but I still can't make it.
Suppose I have a dataframe
library(tidyverse)
df <- tribble(
~id, ~x, ~y, ~z, ~g,
#--|--|--|--|--
"a", 13.1, 14, 4, 1,
"b", 15.2, 7, 5, 0,
"c", 12.5, 10, 1, 0,
"d", 20, 11, 3, 1
)
df
#> # A tibble: 4 x 5
#> id x y z g
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 a 13.1 14 4 1
#> 2 b 15.2 7 5 0
#> 3 c 12.5 10 1 0
#> 4 d 20 11 3 1
and cutoffs for x, y, z columns
cutoffs <- list(
x = 13,
y = 12,
z = 3
)
I want to change the value of each column to 0 or 1, according to the specified cutoffs (different columns, different cutoffs).
This is easy to do with dplyr::if_else
,
df %>%
mutate(x = if_else(x < cutoffs$x, 1, 0)) %>%
mutate(y = if_else(y < cutoffs$y, 1, 0)) %>%
mutate(z = if_else(z < cutoffs$z, 1, 0))
#> # A tibble: 4 x 5
#> id x y z g
#> <chr> <dbl> <dbl> <dbl> <dbl>
#> 1 a 0 0 0 1
#> 2 b 0 1 0 0
#> 3 c 1 1 1 0
#> 4 d 0 1 0 1
However, i want to write a tidyeval
function to do same thing, like this
get_deprivation_df <- function(df, ...) {
cutoffs_vars = enquos(...)
if( length(cutoffs_vars) == 0 ){
stop(paste("please provide cutoffs for each column"))
}
# ...
}
and using
df %>% get_deprivation_df(
cutoffs = list(
x = 13,
y = 12,
z = 3
)
)
I'm a beginner for tidyeval, could you please give me some help and advice?