有什么方法可以改变 View 对不同 类 的工作方式吗?

Is there any way to change the way View works for different classes?

我在 R 中创建了一个基于列表的 S3 class。但是,我希望它像数据框一样显示在视图中。基本上,我希望 View 使用 as.data.frame 方法来查看它,而不是以它显示列表的方式显示它。有什么办法吗?

这是一个简单的例子:

as.myclass <- function(x) {
  x <- list(x = x, y = 1, z = 2)
  class(x) <- "myclass"
  return(x)
}

as.data.frame.myclass <- function(x) {
  return(x$x)
}

View(as.myclass(mtcars))                      # This is what it does
View(as.data.frame(as.myclass(mtcars)))       # This is what I would like the previous command to do

如果我们定义一个方法 as.data.frame.myclass View() 将起作用...除非您使用 Rstudio,它有自己的优先版本,并且行为不同。

如果您使用 utils::View(),您将获得 R gui 输出:

as.myclass <- function(x) {
  class(x) <- "myclass"
  return(x)
}

as.data.frame.myclass <- as.data.frame.list
utils::View(as.myclass(mtcars)) 

现在,如果您使用 Rstudio,它会稍微复杂一些,我们需要覆盖它并使其通用化:

View <- function(x, title) UseMethod("View")
View.default <- function(x, title) eval(substitute(
  get("View", envir = as.environment("package:utils"))(x,title)))
View.myclass <- function(x, title) eval(substitute(
  get("View", envir = as.environment("package:utils"))(as.data.frame(x),title)))
View(as.myclass(mtcars))   

不过,如果您有能力将 data.frame class 与我的class 一起保留,那就更容易了:

as.myclass <- function(x) {
  class(x) <- c("data.frame","myclass")
  return(x)
}
View(as.myclass(mtcars)) # without overriding `View()`!