Tomas
Tomas

Reputation: 59515

Why is argument not passed by apply()?

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?

Upvotes: 0

Views: 63

Answers (2)

MrFlick
MrFlick

Reputation: 206263

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.

Upvotes: 2

user2332849
user2332849

Reputation: 1450

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

mapply(your_function, arg1, arg2, argn

Upvotes: 0

Related Questions