访问带引号的点参数的名称

Access the name of an enquoted dots parameter

我有两个功能:

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)
}

我想 print(paste(nrow(df), "records left after excluding", eval(condition), sep = " ")) 打印一个看起来像 100000 records left after excluded age > 18 的简单字符串,其中 age > 18 是我直接传递给 exclude 函数的过滤器:

exclude(df, age > 18)

我最终得到的输出如下所示:

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

这与我想要的非常接近,但是每个字符向量打印两个字符串而不是 1 个。我怎样才能获得所需的输出?

这里有一个选项

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)

}

-测试

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

数据

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

您可以使用 rlang::enexprs 允许将多个条件传递给单个函数中的点。此外,如果您希望排除条件,请记住反转过滤器:

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")
  }
}

例如:

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