Friedrich
Friedrich

Reputation: 118

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?

Upvotes: 0

Views: 73

Answers (3)

gaut
gaut

Reputation: 5958

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.

Upvotes: 1

zx8754
zx8754

Reputation: 56219

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

Upvotes: 2

jamoreiras
jamoreiras

Reputation: 333

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.

Upvotes: 1

Related Questions