gpt4 book ai didi

r - 如何为自定义数据框重载 RStudio 的 View 函数?

转载 作者:行者123 更新时间:2023-12-04 13:48:04 29 4
gpt4 key购买 nike

我正在使用 RStudio 并希望为特殊分类的 data.frame 定义一个 View 方法,但仍然保留标准 data.frame/matrix 对象的现有 View 方法。

RStudio 默认:

  • 使用 View(x) 时,在“源” Pane 中的表格浏览器中打开 data.frame 或矩阵对象或单击“环境” Pane 中的对象时。

  • 当我尝试使用此代码重新定义方法时,我得到如下所示的行为。我的特殊分类对象以我想要的方式查看,但标准 data.frame 对象不再调用源 Pane 中的电子表格类型浏览器。

    如何添加新 View()我的对象的行为,但也要保持原始行为?
    iris_myclass <- iris
    class(iris_myclass) <- c("myclass", "data.frame")

    View(iris)
    ## opens a tabular data browser in the Source pane
    View(iris_myclass)
    ## opens a tabular data browser in the Source pane

    View <- function(x, title) {
    UseMethod("View")
    }

    View.default <- function(x, title) {
    utils::View(x, title)
    }

    View.myclass <- function(x, title) {
    DT::datatable(x)
    }

    View(iris)
    ## opens an Xwindows Viewer
    View(iris_myclass)
    ## opens an HTML datatable browser in the Viewer pane

    我的设置:RStudio 版本 1.0.136 和
    R version 3.3.2 (2016-10-31)
    Platform: x86_64-apple-darwin13.4.0 (64-bit)
    Running under: macOS Sierra 10.12.2

    locale:
    [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

    attached base packages:
    [1] stats graphics grDevices utils datasets methods base

    other attached packages:
    [1] DT_0.2

    最佳答案

    它确实像这样工作:

    View.default <- function(...) {
    get('View', as.environment('package:utils'))(...)
    }
    utils::Viewmget('View')返回不同的函数。正如@KevinUshey 解释的那样,Rstudio 会覆盖 View在搜索路径上(在 package:utils 环境中),但不在 utils 中命名空间。所以我们不能用 utils::View 访问它,但我们可以使用 mget .

    使用 get而不是 mget甚至更好(感谢@Willem)。

    关于r - 如何为自定义数据框重载 RStudio 的 View 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41532300/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com