1

Let's say I have a function that creates x number of objects based on the length of an input variable. I then want those x number of objects to be used as arguments in a function I supply to my function. Assumign that my number of arguments is variable (based on the number of argument names provided), how can I do this?

Can I do this via a string of argument names perhaps?

A non-working example to illustrate what I'm asking:

(in this case, using arguments created outside the function to simplify the example):

foo <- 1:5
na.rm <- T
func <- mean

f1 <- function(func,arg.names) { 
  func(get(arg.names)) }
f1(func,arg.names = c('foo','na.rm')

How do I do this in a way that get's all arguments from my list?

2 Answers 2

2

We can try with mget

f1 <- function(func,arg.names) { 
      lst <- mget(arg.names, envir = parent.frame())
        func(lst[[1]], na.rm = lst[[2]])
 }

f1(func, arg.names = c('foo', 'na.rm'))
#[1] 3

Or another option is do.call (as mentioned in the @thelatemail's post) but change the name of the first list element to 'x' as x is the 'data' argument in the mean function

## Default S3 method:

mean(x, trim = 0, na.rm = FALSE, ...)

 f1 <- function(func,arg.names) { 
        lst <- mget(arg.names, envir = parent.frame())
        names(lst)[1] <- 'x'
         do.call(func, lst)
     }

f1(func, arg.names = c('foo', 'na.rm'))
#[1] 3
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect! This is exactly what I'm looking for! Thanks @akrun. But now the real question...is this the right (best) way to accomplish what I'm trying to do?? Or is my approach perhaps a "sloppy" or inappropriate approach?
@theforestecologist THanks, Regarding the question, it depends on why you have to go through this route. Perhaps you can post a new question giving more details about the final objective.
1

The magic of ?do.call awaits you:

do.call(func, list(foo, na.rm=na.rm))
#[1] 3

This essentially just creates and runs:

func(foo, na.rm=na.rm)

...where the arguments to func are passed in as a (potentially named) list.

2 Comments

what if I have to supply arguments as strings, vs the object names themselves? (e.g., 'foo' & 'na.rm' vs. foo & na.rm)
@theforestecologist - I think akrun has you covered below.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.