如何捕获对 dplyr::select 中的 data.frame 所做的更改?

How can I capture the changes made to a data.frame in dplyr::select?

我想创建一个 data.frame 的子类,它包含一些关于特定列状态的信息。我认为最好的方法是使用属性 special_col。一个简单的构造函数似乎工作正常:

# Light class that keeps an attribute about a particular special column
new_my_class <- function(x, special_col) {
  stopifnot(inherits(x, "data.frame"))
  attr(x, "special_col") <- special_col
  class(x) <- c("my_class", class(x))
  x
}

my_mtcars <- new_my_class(mtcars, "mpg")
class(my_mtcars) # subclass of data.frame
#> [1] "my_class"   "data.frame"
attributes(my_mtcars)$special_col # special_col attribute is still there
#> $special_col
#> [1] "mpg"

但是,我 运行 遇到了一个问题,即如果列名发生变化,我需要为各种泛型编写方法来更新此属性。如下所示,使用 data.frame 方法将保持属性不变。

library(dplyr)
# Using select to rename a column does not update the attribute
select(my_mtcars, x = mpg) %>%
  attr("special_col")
#> [1] "mpg"

这是我目前对 my_class 方法的幼稚尝试。我着手捕获点,然后解析它们以找出哪些列被重命名,如果它们实际上被重命名则更改属性。

# I attempt to capture the dots supplied to select and replace the attribute
select.my_class <- function(.data, ...) {
  exprs <- enquos(...)
  sel <- NextMethod("select", .data)
  replace_renamed_cols(sel, "special_col", exprs)
}
# This is slightly more complex than needed here in case there is more than one special_col
replace_renamed_cols <- function(x, which, exprs) {
  att <- attr(x, which)
  renamed <- nzchar(names(exprs)) # Bool: was column renamed?
  old_names <- purrr::map_chr(exprs, rlang::as_name)[renamed]
  new_names <- names(exprs)[renamed]
  att_rn_idx <- match(att, old_names) # Which attribute columns were renamed?
  att[att_rn_idx] <- new_names[att_rn_idx]
  attr(x, which) <- att
  x
}
# This solves the immmediate problem:
select(my_mtcars, x = mpg) %>%
  attr("special_col")
#> [1] "x"

不幸的是,我认为这特别脆弱,在其他情况下会失败,如下所示。

# However, this fails with other expressions:
select(my_mtcars, -cyl)
#> Error: Can't convert a call to a string
select(my_mtcars, starts_with("c"))
#> Error: Can't convert a call to a string

我的感觉是,最好在 tidyselect 完成其工作后获取列中的更改,而不是像我所做的那样尝试通过捕获点来生成相同的属性更改。关键问题是:我如何使用 tidyselect 工具来了解当 select 个变量时数据帧会发生什么变化?。理想情况下,我可以 return 跟踪哪些列被重命名为哪些列,哪些列被删除等,并使用它来使属性 special_col 保持最新。

我认为这样做的方法是在 [names<- 方法中对属性更新进行编码,然后默认的 select 方法应该使用这些泛型。 dplyr的下一个大版本应该是这样的。

请参阅 https://github.com/r-lib/tidyselect/blob/8d1c76dae81eb55032bcbd83d2d19625db887025/R/eval-select.R#L152-L156 预览 select.default 的外观。我们甚至可以从 dplyr 中删除 tbl-df 和 data.frame 方法。最后一行很有趣,它调用 [names<- 方法。