r语言 - 有没有办法改变视图在不同类的工作方式?



我在R中创建了一个基于列表的S3类。但是,我希望它像数据框一样显示在视图中。基本上,我希望 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.myclassView()它将起作用...除非您使用 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类与myclass一起保留,那会更容易:

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

相关内容

最新更新