0

I'm writing a package function that needs defaults parameters to work, but whose values have to be taken from processed (other) arguments of the function. As of now, I'm doing it like so :

myfunc <- function(x, y, n=NULL){
  processed <- some_other_func(x,y)
  x <- processed$x
  y <- processed$y
  if(is.null(n)){
    n <- length(intersect(x,y))/3
  }
  # do stuff
}

But ideally, I'd like a default expression to be put instead of NULL because it seems inconsistent if my doc says that the default is length(intersect(x,y))/3.

Do you know of a way I could specify the default parameter to be more comprehensible ?

RoB
  • 1,833
  • 11
  • 23
  • Maybe `missing()` instead of `is.null()`. https://stackoverflow.com/questions/7964830/test-if-an-argument-of-a-function-is-set-or-not-in-r – RLave Apr 12 '19 at 08:35
  • if this default requires the input of other function arguments, I don't really see any better way than what you are doing. – boski Apr 12 '19 at 08:36
  • 1
    Note that `n=NULL`, imo, is a legit default value, just specify in the docs that it'll be set to `length(..)` if missing. – RLave Apr 12 '19 at 08:36

1 Answers1

0

Maybe you could solve it something like this?

default_function <- function(v1, v2)
{
  return((v1 + v2)/2)
}

dummy_function <- function(x, y, n = default_function)
{
  x = x
  y = y
  if(class(n) == "function") n = n(x,y) # if n is any kind of function do it

  print(paste(x, y, n))

}


dummy_function(1, 2)
dummy_function(1, 2, 100)
TinglTanglBob
  • 627
  • 1
  • 4
  • 14
  • Hmm... I'm not sure it would be doable since `default_function` would need the *processed* `x` and `y`. – RoB Apr 12 '19 at 11:35
  • Im not sure if i understand you right, but the default function, stored in n, should be able to recieve the processed x and y values when it is executed in the if-case? – TinglTanglBob Apr 12 '19 at 11:50
  • 1
    But to be honest, i think setting n = NULL and giving an explanation in the docs as @RLave suggested is easier to understand than the suggested method with n = some sort of function here. – TinglTanglBob Apr 12 '19 at 11:57
  • Yes, I guess you're right. People will just have to start reading the doc :P – RoB Apr 12 '19 at 12:00