我想创建一个 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