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是最新的。

4

1 回答 1

1

I think the way to do it is to encode you attribute updating in the [ and names<- methods, then the default select method should use these generics. This should be the case in the next major version of dplyr.

See https://github.com/r-lib/tidyselect/blob/8d1c76dae81eb55032bcbd83d2d19625db887025/R/eval-select.R#L152-L156 for a preview of what select.default will look like. We might even remove tbl-df and data.frame methods from dplyr. The last line is of interest, it invokes [ and names<- methods.

于 2019-11-27T08:04:07.813 回答