在 RStudio 中记录 R 包中的 R6 类和方法

2024-02-10

我正在努力处理 R6 类及其方法的文档。我的目标是在 RStudio 中获得方法的自动完成功能。目前,我只得到方法的名称,但没有得到我通常使用的帮助信息roxygen2用参数等记录函数

目前,这是我的班级:

#' @importFrom R6 R6Class
MQParameters <- R6::R6Class(
  'MQParameters',
  public=list(
    initialize=function(file_path=NA) {
      private$location <- file_path
      mq_parameters <- read.delim(file_path, stringsAsFactors=FALSE)
      mq_parameters <-
        setNames(mq_parameters$Value, mq_parameters$Parameter)
      private$mq_version <- unname(mq_parameters['Version'])
      private$fasta_file <-
        gsub('\\\\', '/', strsplit(mq_parameters['Fasta file'], ';')[[1]])
    },
    # this method returns the version
    getVersion=function() {
      private$mq_version
    },
    # this methods returns the fastafile.
    # @param new_param it is possible to rewrite the basedir.
    getFastaFile=function(new_basedir=NA) {
      if(is.na(new_basedir)) {
        private$fasta_file
      } else {
        file.path(new_basedir, basename(private$fasta_file))
      }
    }
  ),
  private=list(
    location=NULL,
    mq_version=NULL,
    fasta_file=NULL
  )
)

如果您有兴趣测试这个类,这里​​有一个可重现的例子:

df <- data.frame(Parameter=c('Version', 'Fasta file'),
                 Value=c('1.5.2.8','c:\\a\\b.fasta'))
write.table(df, 'jnk.txt', sep='\t', row.names=F)

p <- MQParameters$new('jnk.txt')
p$getVersion()
# [1] "1.5.2.8"
p$getFastaFile()
# [1] "c:/a/b.fasta"
p$getFastaFile(new_basedir='.')
# [1] "./b.fasta"

我不知道如何记录参数,因为参数实际上属于创建者而不属于类。函数中其他方法的参数怎么样?
使用类的方法来记录类的首选方法是什么?

我很想从 RStudio 获得“正常”功能,比如点击F1直接进入帮助页面。

通过搜索互联网,我在 Github 上看到了一些关于这个主题的报道,但它们已经存在一年多了。

Update

感谢 的回答mikeck我现在有一个关于该类及其方法的很好的文档。但我仍然缺乏的是获得函数/方法及其参数的提示的可能性,就像这个常见函数的屏幕截图一样:

我想知道是否可以以某种方式手动注册我的函数,但由于它没有特定的名称(它总是与您用于对象的变量对象名结合在一起)OBJECTNAME$methodeCall())我不知道该怎么做。


我的理解是,记录一个NULL具有相同的对象@name作为您的班级,因为这提供了最大的灵活性。我在我的一个包中使用了 R6 类;你可以查看氧气here https://github.com/mkoohafkan/pysockr/blob/master/R/pyr6.r。我在下面提供了一个小样本:

#' Python Environment
#' 
#' The Python Environment Class. Provides an interface to a Python process.
#' 
#' 
#' @section Usage:
#' \preformatted{py = PythonEnv$new(port, path)
#'
#' py$start()
#' 
#' py$running
#' 
#' py$exec(..., file = NULL)
#' py$stop(force = FALSE)
#' 
#' }
#'
#' @section Arguments:
#' \code{port} The port to use for communication with Python.
#' 
#' \code{path} The path to the Python executable.
#' 
#' \code{...} Commands to run or named variables to set in the Python process.
#'
#' \code{file} File containing Python code to execute.
#' 
#' \code{force} If \code{TRUE}, force the Python process to terminate
#'   using a sytem call.
#' 
#' @section Methods:
#' \code{$new()} Initialize a Python interface. The Python process is not 
#'   started automatically.
#'   
#' \code{$start()} Start the Python process. The Python process runs 
#'   asynchronously.
#'
#' \code{$running} Check if the Python process is running.
#'   
#' \code{$exec()} Execute the specified Python 
#'   commands and invisibly return printed Python output (if any).
#'   Alternatively, the \code{file} argument can be used to specify
#'   a file containing Python code. Note that there will be no return 
#'   value unless an explicit Python \code{print} statement is executed.
#' 
#' \code{$stop()} Stop the Python process by sending a request to the 
#'   Python process. If \code{force = TRUE}, the process will be 
#'   terminated using a system call instead.
#'
#' @name PythonEnv
#' @examples
#' pypath = Sys.which('python')
#' if(nchar(pypath) > 0) { 
#'   py = PythonEnv$new(path = pypath, port = 6011)
#'   py$start()
#'   py$running
#'   py$stop(force = TRUE)
#' } else 
#' message("No Python distribution found!")
NULL

#' @export
PythonEnv = R6::R6Class("PythonEnv", cloneable = FALSE,
  # actual class definition...

还有其他替代(但类似)的实现;这个例子 https://github.com/Ermlab/lightning-rstat/blob/41ba35d647d0f6953055eb61c87d950c6b21cc97/LightningR/R/lightning.R uses @docType class这可能更适合您:

#' Class providing object with methods for communication with lightning-viz server
#'
#' @docType class
#' @importFrom R6 R6Class
#' @importFrom RCurl postForm
#' @importFrom RJSONIO fromJSON toJSON
#' @importFrom httr POST
#' @export
#' @keywords data
#' @return Object of \code{\link{R6Class}} with methods for communication with lightning-viz server.
#' @format \code{\link{R6Class}} object.
#' @examples
#' Lightning$new("http://localhost:3000/")
#' Lightning$new("http://your-lightning.herokuapp.com/")
#' @field serveraddress Stores address of your lightning server.
#' @field sessionid Stores id of your current session on the server.
#' @field url Stores url of the last visualization created by this object.
#' @field autoopen Checks if the server is automatically opening the visualizations.
#' @field notebook Checks if the server is in the jupyter notebook mode.
#' #' @section Methods:
#' \describe{
#'   \item{Documentation}{For full documentation of each method go to https://github.com/lightning-viz/lightining-r/}
#'   \item{\code{new(serveraddress)}}{This method is used to create object of this class with \code{serveraddress} as address of the server object is connecting to.}
#'
#'   \item{\code{sethost(serveraddress)}}{This method changes server that you are contacting with to \code{serveraddress}.}
#'   \item{\code{createsession(sessionname = "")}}{This method creates new session on the server with optionally given name in \code{sessionname}.}
#'   \item{\code{usesession(sessionid)}}{This method changes currently used session on the server to the one with id given in \code{sessionid} parameter.}
#'   \item{\code{openviz(vizid = NA)}}{This method by default opens most recently created by this object visualization. If \code{vizid} parameter is given, it opens a visualization with given id instead.}
#'   \item{\code{enableautoopening()}}{This method enables auto opening of every visualisation that you create since that moment. Disabled by default.}
#'   \item{\code{disableautoopening()}}{This method disables auto opening of every visualisation that you create since that moment. Disabled by default.}
#'   \item{\code{line(series, index = NA, color = NA, label = NA, size = NA, xaxis = NA, yaxis = NA, logScaleX = "false", logScaleY = "false")}}{This method creates a line visualization for vector/matrix with each row representing a line, given in \code{series}.}
#'   \item{\code{scatter(x, y, color = NA, label = NA, size = NA, alpha = NA, xaxis = NA, yaxis = NA)}}{This method creates a scatterplot for points with coordinates given in vectors \code{x, y}.}
#'   \item{\code{linestacked(series, color = NA, label = NA, size = NA)}}{This method creates a plot of multiple lines given in matrix \code{series}, with an ability to hide and show every one of them.}
#'   \item{\code{force(matrix, color = NA, label = NA, size = NA)}}{This method creates a force plot for matrix given in \code{matrix}.}
#'   \item{\code{graph(x, y, matrix, color = NA, label = NA, size = NA)}}{This method creates a graph of points with coordinates given in \code{x, y} vectors, with connection given in \code{matrix} connectivity matrix.}
#'   \item{\code{map(regions, weights, colormap)}}{This method creates a world (or USA) map, marking regions given as a vector of abbreviations (3-char for countries, 2-char for states) in \code{regions} with weights given in \code{weights} vector and with \code{colormap} color (string from colorbrewer).}
#'   \item{\code{graphbundled(x, y, matrix, color = NA, label = NA, size = NA)}}{This method creates a bundled graph of points with coordinates given in \code{x, y} vectors, with connection given in \code{matrix} connectivity matrix. Lines on this graph are stacked a bit more than in the \code{graph} function.}
#'   \item{\code{matrix(matrix, colormap)}}{This method creates a visualization of matrix given in \code{matrix} parameter, with its contents used as weights for the colormap given in \code{colormap} (string from colorbrewer).}
#'   \item{\code{adjacency(matrix, label = NA)}}{This method creates a visualization for adjacency matrix given in \code{matrix} parameter.}
#'   \item{\code{scatterline(x, y, t, color = NA, label = NA, size = NA)}}{This method creates a scatterplot for coordinates in vectors \code{x, y} and assignes a line plot to every point on that plot. Each line is given as a row in \code{t} matrix.}
#'   \item{\code{scatter3(x, y, z, color = NA, label = NA, size = NA, alpha = NA)}}{This method creates a 3D scatterplot for coordinates given in vectors \code{x, y, z}.}
#'   \item{\code{image(imgpath)}}{This method uploads image from file \code{imgpath} to the server and creates a visualisation of it.}
#'   \item{\code{gallery(imgpathvector)}}{This method uploads images from vector of file paths \code{imgpathvector} to the server and creates a gallery of these images.}}


Lightning <- R6Class("Lightning",
...
)

EDIT

如果您正在寻找一种方法来在尝试使用类方法时显示 RStudio 工具提示...不幸的是,我认为您不会找到一种不需要以消除以下问题的方式对类进行编码的解决方案: R6 类的便利性和功能性。

@f-privé 提供了一个答案,可以做你想做的事——只需将该逻辑扩展到所有方法即可。例如,myclass$my_method而是通过以下方式访问

my_method = function(r6obj) {
  r6obj$my_method()
}
obj$my_method()
my_method(obj)      # equivalent

换句话说,您需要为每个方法创建一个包装器。这显然比使用obj$my_method(),并且可能首先就失去了使用 R6 类的用处。

这里的问题实际上是 RStudio。 IDE 没有通过分析代码来识别 R6 类的好方法,并且无法区分已定义类的方法和列表或环境的元素。此外,RStudio 无法提供任意函数的帮助,例如:

na.omit()         # tooltip shows up when cursor is within the parentheses
foo = na.omit
foo()             # no tooltip

这与调用特定 R6 对象的方法非常相似。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 RStudio 中记录 R 包中的 R6 类和方法 的相关文章

随机推荐

  • 为左浮动 div 或列表设置文本溢出省略号

    这是我想做的 创建一个仅占用所需空间 水平 的列表 即最长的列表元素 当列表不适合页面时 修剪列表文本并显示省略号 我使用的组合white space nowrap and text overflow ellipsis 对于普通列表来说它工
  • 在ios中使用AVAudioSession时出错

    我用了这些代码 void viewDidLoad AVAudioSession sharedInstance setDelegate self AVAudioSession sharedInstance setCategory AVAudi
  • 如何以八度增加命令窗口的字体大小

    我试图弄清楚如何增加命令窗口文本 我想通了legend legend fontsize 10 Low fontsize 10 Medium fontsize 10 High 我尝试做同样的事情 但是command command windo
  • 谷歌地图无法正确呈现

    我正在使用主干和 gmaps js 由于某种原因 地图无法正确渲染 控制器没有正确显示 信息窗口的渲染也很奇怪 我正在使用gmaps js 库 https github com HPNeo gmaps 我什至不知道如何调试这个东西 这是我的
  • 计数信号量和二进制信号量之间的区别

    计数和二进制信号量有什么区别 我在某处看到的是 两者都可以控制 N 个请求资源的进程 两者都拥有自由邦 二进制信号量和计数信号量可以保护的资源数量是否有限制 两者都只允许一个进程一次使用一种资源 还有其他区别吗 上述属性是否正确 实际上 这
  • python语法错误无效语法[重复]

    这个问题在这里已经有答案了 我是 Python 编程语言的新手 我买了一本书并且一直在读 这本书的名字是 3x Python 初学者编程第三版 我正在努力将迄今为止所学到的知识付诸实践 我有一个我不明白的问题 我知道它很简单 但我不确定如何
  • 如何在 SQLAlchemy for MSSQL 中设置架构?

    我目前这样做 usr bin env python 3rd party modules from sqlalchemy import create engine requires pymssql local modules from con
  • 如何尽可能快地将大量记录插入MySql数据库

    我有一个如下所示的数据库表 create table temperature id int unsigned not null auto increment primary key temperature double 在我的程序中 我将大
  • 从 Xamarin.Forms 应用程序打印

    我是 Xamarin 新手 目前正在使用 Xamarin Forms 开发示例或 概念证明 应用程序 我应该从这个应用程序执行打印任务 尽管我现在还不确定要打印什么 屏幕 标签内容 文件等 无论哪种方式 从 Xamarin Forms 应用
  • 使用来自互联网的图像更新 Android 小部件(使用异步任务)

    我有一个简单的 Android 小部件 我想用互联网上的图像进行更新 我可以在小部件上显示静态图像 没有问题 有人告诉我 您需要为此使用异步任务 而我对此没有太多经验 这是我的小部件 Override public void onUpdat
  • Docker Rancher - 从 WSL 使用 docker 时权限被拒绝

    我已经在 Windows 10 上使用 dockerd 选项安装了 Docker Rancher 并为我当前的 WSL 发行版 Ubuntu 安装了 WSL 当我尝试在 WSL2 中使用 docker 时 出现以下错误 fpapi xxx
  • Java 中 int 转换为数组 char

    我试图在不使用字符串操作的情况下将整数转换为字符数组 我的尝试是 int number 12 char test Character toChars number for char c test System out println c 没
  • 在多对多关系上添加元素

    我正在做一个项目 从学校的角度 你可以计算每个学生的平均值 您可以在一个屏幕上注册学生 第一个实体 在另一个屏幕上注册科目 第二个实体 学生有姓名 电子邮件 成绩和平均分作为属性 科目有姓名 它们彼此之间是多对多关联的 我正在尝试为每个学生
  • UITableView 和单元格重用

    我有一个UITableView我已经子类化了UITableViewCell 叫它CustomCell 所以它有几个标签和一个UIImageView 只有某些单元格才会真正显示图像 这是我的代码tableView cellForRowAtIn
  • 如何获取AVPlayer的视频帧?

    我有 PlayerView 类用于显示 AVPlayer 的播放 代码来自文档 https developer apple com library archive documentation AudioVideo Conceptual AV
  • 来自 StringIO 源的 Python xml etree DTD?

    我正在调整以下代码 通过中的建议创建这个问题 https stackoverflow com questions 2835077 lxml unicode entity parse problems 它采用 XML 文件及其 DTD 并将它
  • 在 Vista 上安装后无法使用 gem 和 ruby​​ 命令

    我昨天按照此站点上的说明在 Vista 32 位上安装了 Ruby 和 Ruby on Rails http rubyonrails org down http rubyonrails org down 所以我下载了安装程序 然后是 Gem
  • 当数据量较小时,node.js response.write(data) 需要很长时间

    我注意到 Node js 中以下代码的性能出现了奇怪的行为 当尺寸为content为1 4KB 请求的响应时间大约为16ms 然而 当尺寸为content只有988字节 请求的响应时间奇怪地长得多 大致200ms response writ
  • AngularJS - ngSwitch 和 ng Click 在 ng Repeat 中不起作用

    我想显示列表的元素 这要归功于ngSwitch但我不知道该怎么做ngRepeat 我一开始没有列出清单 只是为了了解如何ngSwitch工作并向您展示我想要做什么 这里有一个 jsFiddle 可以帮助您理解 jdFiffle 1 http
  • 在 RStudio 中记录 R 包中的 R6 类和方法

    我正在努力处理 R6 类及其方法的文档 我的目标是在 RStudio 中获得方法的自动完成功能 目前 我只得到方法的名称 但没有得到我通常使用的帮助信息roxygen2用参数等记录函数 目前 这是我的班级 importFrom R6 R6C