如何在dplyr :: select中捕获对数据框所做的更改?

4

我想创建一个 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工具了解在选择变量时数据帧将发生哪些更改? 理想情况下,我可以返回一些内容,以跟踪哪些列被重命名为另一些列,哪些列被删除等,并使用该内容来保持属性special_col的最新状态。


我看这可能有帮助?我不是很想转换成data.table代码,但我会查看其源代码,看看它在翻译之前如何捕获。 - Calum You
1个回答

1

您可能会遇到问题,因为我们最近才开始使用泛型来制作默认方法。请将非泛型默认方法报告为错误。 - Lionel Henry
感谢您对此的预览!我确实需要找出关于 [names<- 方法的最佳实现方式。然而,如果我的子类不继承自 data.frame,那么这种方法是否有意义呢?因为目前我可以使用 NextMethod() 来进行实际的子集操作。或者您是在说 select 最终会在所有地方都使用 [names<- 吗? - Calum You
我认为select()函数将在默认和数据框方法中使用[names<-(这可能会合并)。 - Lionel Henry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接