var_summary <- function(data, var) {
data %>%
summarise(n = n(), min = min({{ var }}), max = max({{ var }}))
}
mtcars %>%
group_by(cyl) %>%
var_summary(mpg)
When you have the data-variable in a function argument (i.e. an env-variable that holds a promise2), you need to embrace the argument by surrounding it in doubled braces, like filter(df, {{ var }})
.
for (var in names(mtcars)) {
mtcars %>% count(.data[[var]]) %>% print()
}
Note that .data is not a data frame; it’s a special construct, a pronoun, that allows you to access the current variables either directly, with .data$x or indirectly with .data[[var]]. Don’t expect other functions to work with it.
If you want to use the names of variables in the output, you can use glue syntax in conjunction with :=:
my_summarise4 <- function(data, expr) {
data %>% summarise(
"mean_{{expr}}" := mean({{ expr }}),
"sum_{{expr}}" := sum({{ expr }}),
"n_{{expr}}" := n()
)
}
my_summarise5 <- function(data, mean_var, sd_var) {
data %>%
summarise(
"mean_{{mean_var}}" := mean({{ mean_var }}),
"sd_{{sd_var}}" := sd({{ sd_var }})
)
}
If you want to take an arbitrary number of user supplied expressions, use ...
. This is most often useful when you want to give the user full control over a single part of the pipeline, like a [group_by()](https://dplyr.tidyverse.org/reference/group_by.html)
or a [mutate()](https://dplyr.tidyverse.org/reference/mutate.html)
.
my_summarise <- function(.data, ...) {
.data %>%
group_by(...) %>%
summarise(mass = mean(mass, na.rm = TRUE), height = mean(height, na.rm = TRUE))
}
starwars %>% my_summarise(homeworld)
#> # A tibble: 49 x 3
#> homeworld mass height
#> <chr> <dbl> <dbl>
#> 1 Alderaan 64 176.
#> 2 Aleen Minor 15 79
#> 3 Bespin 79 175
#> 4 Bestine IV 110 180
#> # … with 45 more rows
starwars %>% my_summarise(sex, gender)
#> `summarise()` has grouped output by 'sex'. You can override using the `.groups` argument.
#> # A tibble: 6 x 4
#> # Groups: sex [5]
#> sex gender mass height
#> <chr> <chr> <dbl> <dbl>
#> 1 female feminine 54.7 169.
#> 2 hermaphroditic masculine 1358 175
#> 3 male masculine 81.0 179.
#> 4 none feminine NaN 96
#> # … with 2 more rows
https://dplyr.tidyverse.org/articles/programming.html
https://bookdown.org/wangminjie/R4DS/tidyverse-beauty-of-across1.html
网友评论