Debangan Dey
Debangan Dey

Reputation: 11

Creating a function based on varying argument names in R

I want to create a function that makes functions based on varying arguments and body.

For example, take n=2 and a=paste0("a",1:2n), i.e., a=c("a1","a2","a3","a4").

Then I want to create a function as follows -

fa = function(a1,a2,a3,a4) { 
args_fa = unlist(as.list(environment())) # catch all the arguments as a list
v1 = args_fa[1:n] # assign values to baseline function arguments
v2 = args_fa[(n+1):2*n]
f(v1,v2)
} 

Similarly for n=3, I want the function to look like this -

fa = function(a1,a2,a3,a4,a5,a6) { 
args_fa = unlist(as.list(environment())) # catch all the arguments as a list
v1 = args_fa[1:n] # assign values to baseline function arguments
v2 = args_fa[(n+1):2*n]
f(v1,v2)
} 

The f inside the function is a baseline function (fixed) and doesn't vary. My question is how do I create fa based on changing n?

Upvotes: 1

Views: 49

Answers (1)

r2evans
r2evans

Reputation: 160447

Use the ellipsis ..., and include n in the argument list:

fa <- function(n, ...) {
  stopifnot(length(n) == 1L, n > 0)
  args_fa <- unlist(list(...))
  v1 <- args_fa[1:n]
  v2 <- args_fa[(n+1):(2*n)]
  f(v1, v2)
}

Or alternatively, putting n as the last. This requires that n be a named-argument, it cannot be passed as a positional argument.

fa <- function(..., n) {
  stopifnot(length(n) == 1L, n > 0)
  args_fa <- unlist(list(...))
  v1 <- args_fa[1:n]
  v2 <- args_fa[(n+1):(2*n)]
  f(v1, v2)
}

or if you are always going to have a vector or list of the arguments, then perhaps

fa <- function(args_fa, n) {
  stopifnot(length(n) == 1L, n > 0)
  v1 <- args_fa[1:n]
  v2 <- args_fa[(n+1):(2*n)]
  f(v1, v2)
}

Upvotes: 2

Related Questions