简体   繁体   English

使用 roxygen2 的 R 包中具有相同的功能但具有两个不同的名称?

[英]Same function but with two different names in an R package using roxygen2?

I want to create two functions that are exactly the same but have different names in a roxygen2-made R package.我想在 roxygen2 制作的 R 包中创建两个完全相同但名称不同的函数。

Desired outcome期望的结果

To be very clear, suppose非常清楚,假设

first <- function(x) {
  x + 2
}

I would like another function second such that我想要second功能,这样

identical(first, second)
# [1] TRUE

What I know so far到目前为止我所知道的

A function can be given an alias , but that doesn't mean its alias is a callable function - rather, it means that you can call ?myalias to display the help file for the original function .一个函数可以被赋予一个别名,但这并不意味着它的别名是一个可调用的函数——相反,这意味着你可以调用?myalias显示原始函数的帮助文件 But myalias is not a callable function within the package - ie you can't actually use it for anything other than ?但是myalias不是包中的可调用函数——也就是说,除了? . .

From Hadley's documentation:从哈德利的文档:

An alias is another name for the topic that can be used with ?.别名是可以与 ? 一起使用的主题的另一个名称。

An inelegant solution不雅的解决方案

The same function under two different names is possible by brute force - ie by duplicating the file in which the original function is declared and simply changing its name in the duplicate code.可以通过蛮力使用两个不同名称的相同函数 - 即通过复制声明原始函数的文件并简单地在重复代码中更改其名称。

This is obviously tedious, violates DRY , and introduces bloat.这显然很乏味,违反了DRY并引入了膨胀。

Question

Is there a better way;有没有更好的办法; one that doesn't involve large scale duplication of code?一个不涉及大规模重复代码的?

Use

#' @rdname first
#' @export
second <- first

Your example你的榜样

So if first.R initially looked like this所以如果first.R最初看起来像这样

#' A function that adds 2
#' @name first
#' @usage first(x)
#' @param x a number
#' @export

first <- function(x) {
  x + 2
}

Then simply include the extra lines of code like so (the last 3 lines are all that change)然后像这样简单地包含额外的代码行(最后 3 行都是变化的)

#' A function that adds 2
#' @name first
#' @usage first(x)
#' @param x a number
#' @export

first <- function(x) {
  x + 2
}

#' @rdname first
#' @export
second <- first

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM