'How to make function aliases?

I am trying to create aliases for functions in R.

For example, to get the length of a vector in R:

length(the_vector)
#returns the length of the vector

I want to create an alias of the function called "len":

len(the_vector)
#will also return the length of the vector

Is there a way to do this? Key points that I want is that I want the alias to be able to take all arguments that could be taken by the original function, and also that the alias does not replace the original function. (i.e. in the example above, calling either length(the_vector) or len(the_vector) would provide the same result?



Solution 1:[1]

The comment from @russ-hyde provides the basis for an answer. Including:

len <- base::length

in your .R file creates a variable that can be used in every way that base::length can be used.

As long as the "alias definition" is always run as part of the source file that uses it used, this does not make it less portable. There is a case that this reduces legibility of your code, however, since collaborators may not know what to use it for.

There is also the possibility that defining len will cause a name conflict. But on the other hand, you might be doing this to avoid a name conflict – if, for example, you have loaded a package that defines a length() function you could use len() for the standard one. Not that in this case the base:: prefix becomes very important to disambiguate between the multiple objects you might want to be aliasing for.

For example, dplyr overloads the filter function and is widely used. So if you need to use the original filter function for time series, you might want to define:

tsfilter <- stats::filter

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Magnus