Search code examples
rroxygen2

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.

Desired outcome

To be very clear, suppose

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

I would like another function second such that

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. But myalias is not a callable function within the package - i.e. you can't actually use it for anything other than ?.

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 - i.e. 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.

Question

Is there a better way; one that doesn't involve large scale duplication of code?


Solution

  • Use

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

    Your example

    So if first.R initially looked like this

    #' 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)

    #' 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