socialscientist
socialscientist

Reputation: 4272

R: Dynamic assignment to function argument based on other arguments

I am writing a function with two arguments and I want the default vector assigned to an argument to be a vector of NA of the same length as the input to the other argument of arbitrary length. In psuedo-code, I want my_function <- function(foo, bar = rep(NA, length(foo))){}. The issue with this approach is that foo is not an initialized object and so length(foo) throws an error. Is there some way of doing this without first initializing the object for assigning to the foo argument?

Upvotes: 1

Views: 213

Answers (1)

duckmayr
duckmayr

Reputation: 16940

This sort of thing does not throw an error:

f <- function(foo, bar = rep(NA, length(foo))) {
    print(foo)
    print(bar)
}

f(1:10)

 [1]  1  2  3  4  5  6  7  8  9 10
 [1] NA NA NA NA NA NA NA NA NA NA

Upvotes: 1

Related Questions