【问题标题】:How can I capture the changes made to a data.frame in dplyr::select?如何捕获对 dplyr::select 中的 data.frame 所做的更改?
【发布时间】:2019-11-26 22:26:59
【问题描述】:

我想创建一个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 代码,但我会看看它的来源,看看它是如何在翻译之前进行捕获的

标签: r dplyr tidyeval tidyselect


【解决方案1】:

我认为这样做的方法是在[names&lt;- 方法中对属性更新进行编码,那么默认的选择方法应该使用这些泛型。在 dplyr 的下一个主要版本中应该是这种情况。

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

【讨论】:

  • 您可能会遇到问题,因为我们最近才开始将默认方法设为泛型。请将非泛型默认方法报告为错误。
  • 感谢您预览对此的想法!我确实需要找出使用[names&lt;- 方法的最佳方法。但是,当我的子类没有从data.frame 继承时,这种方法是否有意义,因为目前我可以使用NextMethod() 来进行实际的子集化?或者你是说select 最终会在任何地方使用[names&lt;-
  • 我认为select() 将在默认和数据框方法中使用[names&lt;-(最终可能会被合并)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 2021-07-06
  • 2014-08-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
相关资源
最近更新 更多