Search code examples
rnse

Access the name of an enquoted dots parameter


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?


Solution

  • 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