Access the name of an enquoted dots parameter

65 views Asked by At

I have two functions:

exclude <- function(df, ...) {
  dots <- rlang::enquos(...)
  for(i in 1:length(dots)) {
    df <- exclude_cycle(df, dots[[i]])
  }
  return(df)
}

exclude_cycle <- function(df, condition) {
  df <- dplyr::filter(df, !!condition)
  print(paste(nrow(df), "records left after excluding", eval(condition), sep = " "))
  return(df)
}

I would like print(paste(nrow(df), "records left after excluding", eval(condition), sep = " ")) to print a simple string that looks like 100000 records left after excluded age > 18 where age > 18 is a filter I pass directly to the the exclude function:

exclude(df, age > 18)

I end up instead with an output that looks like:

[1] "100000 records left after excluding ~"         "100000 patients left after excluding age >= 18"

Which is very close to what I want, but is printing two strings per character vector rather than 1. How can I achieve the desired output?

2

There are 2 answers

0
Allan Cameron On BEST ANSWER

You can use rlang::enexprs to allow multiple conditions to be passed to the dots in a single function. Also, remember to invert the filter if you wish to exclude the conditions:

exclude <- function(df, ...) {
  dots <- rlang::enexprs(...)
  for(i in seq_along(dots)){
    df <-  dplyr::filter(df, !(!!(dots[[i]])))
    cat(nrow(df), "records left after excluding", as.character(dots[i]), "\n")
  }
}

So for example:

df <- data.frame(letters = rep(LETTERS[1:3], 10),
                 numbers = 1:30)

exclude(df, letters == "A", numbers < 15)
#> 20 records left after excluding letters == "A" 
#> 11 records left after excluding numbers < 15 
0
akrun On

Here is an option

exclude_cycle <- function(df, condition) {
  df <- dplyr::filter(df, !!condition)
  print(paste(nrow(df), "records left after excluding", 
           as.list(eval(condition))[-1], sep = " "))
  return(df)

}

-testing

exclude(df, age > 18)
#[1] "2 records left after excluding age > 18"
#  age
#1  42
#2  19

data

df <- data.frame(age = c(42, 19, 3))