简体   繁体   中英

Assign new name to a defined function in R

I have two bandwidth functions bandwidth_a() and bandwidth_b() . Dependent on the task at hand either one needs to be applied. I have other functions which require a bandwidth call.

Is it possible to have my other functions call a generic bandwidth() and before the call of those functions set either bandwidth() <- bandwidth_a() or bandwidth() <- bandwidth_b() ?

Or how can this requirement be fulfilled?

Using match.fun :

bandwidth_a <- function() "A"
bandwidth_b <- function() "B"

x <- "a"
bandwidth <- match.fun(paste0("bandwidth_", x))
bandwidth()
# [1] "A"

x <- "b"
bandwidth <- match.fun(paste0("bandwidth_", x))
bandwidth()
# [1] "B"

But I'd prefer a generic function as suggested by @CatalystRPA

You can do that by using get

>bandwith_a = function() return('A')

>bandwith_b = function() return('B')

>bandwith = get("bandwith_a")

>bandwith()
[1] "A"
>bandwith = get("bandwith_b")

>bandwith()
[1] "B"

Also please note that you might have to specify the environment if you are calling get from inside one function.

I would just use a type argument.

    bandwidth <- function(x, type = "a") {
      if(type == "a") {
        result <- bandwidth_a(x)
      } 
      if(type == "b") {
        result <- bandwidth_b(x)
      } 
    result
    }

In case your behaviour depends on the type ( class ) of the input, you could also define a generic function, check out Advanced R by Hadley .

A generic function defines an interface, which uses a different implementation depending on the class of an argument (almost always the first argument). Many base R functions are generic, including the important print()


EDIT if you just have an R script you'd like to run through command line, another similar solution is to use Command line arguments such as:

Rscript example.R –type=a

Then you'd pass the type as argument to the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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