0

After really annoying and long debugging, I found that apply() does not pass arguments to functions via ...! Here is a simplified example (this is a simplified example to demonstrate the error):

A <- matrix(0, nrow = 2, ncol = 2)
apply(A, 1, function (x, ...) { cat("argument arg1: "); print(arg1); }, arg1 = 10)
# Argument arg1: Error in print(arg1) (from #1) : object 'arg1' not found

Do you have any idea why or what to do with this? Workaround is obvious, to list all arguments instead of using ..., which is anoying since I use this as a wrapper for other more complex functions. Any thoughts?

Tomas
  • 57,621
  • 49
  • 238
  • 373

2 Answers2

2

The problem isn't that that argument is not being passed to the function (it is), the problem is you are not "catching" it via a named parameter. This works for example

apply(A, 1, function (x, ..., arg1) { cat("argument arg1: "); print(arg1); }, arg1 = 10)

And we can use that variable as arg1 in the function because we caught it. Otherwise it's left inside the ... so you can pass it along to another function. For example we can just pass everything to list like this...

apply(A, 1, function (x, ...) { print(list(...)) }, arg1 = 10)

So since your function uses ... those values that aren't named stay "in" the dots. In order to get them out you need to capture them as arguments.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
0

When you want to pass more than one argument, you may use mappy() instead.

mapply(your_function, arg1, arg2, argn

emilliman5
  • 5,816
  • 3
  • 27
  • 37
user2332849
  • 1,421
  • 1
  • 9
  • 12
  • Only if you need to iterate over all those arguments in parallel, which it doesn't seem like OP wants. – Axeman Mar 06 '20 at 21:21