Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b-rodrigues/3f4eac56dec315d9f0ef1df9063d7e84 to your computer and use it in GitHub Desktop.
Save b-rodrigues/3f4eac56dec315d9f0ef1df9063d7e84 to your computer and use it in GitHub Desktop.
get_counts <- function(dataset, var){
dataset %>%
group_by(am) %>%
mutate("change_{{var}}" := n_distinct({{var}})) %>%
mutate(total = across(starts_with("change"), identity)) %>%
mutate(total = unlist(total)) %>%
filter(total == 11) %>%
select(-total)
}
get_counts(mtcars, hp)
@gtm19
Copy link

gtm19 commented Jun 14, 2022

@b-rodrigues this works, but I'm not entirely sure it's the most efficient way:

get_counts <- function(dataset, var) {
  var <- rlang::enexpr(var)
  new_var <- glue::glue("change_{eval(quote(var))}")
  dataset %>%
    dplyr::group_by(am) %>%
    dplyr::mutate({{new_var}} := dplyr::n_distinct({{var}})) %>% 
    dplyr::filter(.data[[new_var]] == 11)
}

@b-rodrigues
Copy link
Author

@b-rodrigues this works, but I'm not entirely sure it's the most efficient way:

get_counts <- function(dataset, var) {
  var <- rlang::enexpr(var)
  new_var <- glue::glue("change_{eval(quote(var))}")
  dataset %>%
    dplyr::group_by(am) %>%
    dplyr::mutate({{new_var}} := dplyr::n_distinct({{var}})) %>% 
    dplyr::filter(.data[[new_var]] == 11)
}

This is quite nice, and more efficient than my "solution"! Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment