使用向量元素作为多个参数的函数的输入

时间:2022-01-28 16:00:11

This should be simple but I can't figure it out. Suppose I have a function with n arguments, say:

这应该很简单,但我无法弄清楚。假设我有一个带有n个参数的函数,比如说:

example <- function(a, b, c){a*b + c}

I also have a vector x of length n and want to use that as an input for the function, that is: I want to evaluate

我还有一个长度为n的向量x,并希望将其用作函数的输入,即:我想评估

example(x[1], x[2], x[3])

Of course typing this is not so bad for n = 3 but it becomes annoying from n = 5 onwards. So ideally I would just type

当然,对于n = 3,输入这个并不是那么糟糕,但是从n = 5开始它会变得烦人。理想情况下,我只想输入

example(x)

and have R understand what I mean, but that doesn't work. (It will tell me argument b missing with no default, apparently taking all of x to be a and then having nothing left to work with.)

让R理解我的意思,但这不起作用。 (它会告诉我参数b缺失,没有默认值,显然将所有x都作为a然后没有任何东西可以使用。)

So is there some trick to do this, e.g. by automatically generating the code "a = x[1]; b = x[2]; c = x[3]" and then magically having this unquoted and evaluated inside example before the rest of the definition?

那么有一些技巧可以做到这一点,例如通过自动生成代码“a = x [1]; b = x [2]; c = x [3]”然后在定义的其余部分之前神奇地将这个未引用并在内部进行评估?

1 个解决方案

#1


0  

You can solve this problem with do.call. But you must coerce the function's argument (do.call's second argument) to list.

你可以用do.call解决这个问题。但是你必须强制函数的参数(do.call的第二个参数)才能列出。

example <- function(a, b, c){a*b + c}

x <- 1:3
do.call(example, as.list(x))
#[1] 5

However, note that this will fail if the vector is too short or too long:

但请注意,如果向量太短或太长,这将失败:

y <- 1:4
do.call(example, as.list(y))
#Error in (function (a, b, c)  : unused argument (4)

#1


0  

You can solve this problem with do.call. But you must coerce the function's argument (do.call's second argument) to list.

你可以用do.call解决这个问题。但是你必须强制函数的参数(do.call的第二个参数)才能列出。

example <- function(a, b, c){a*b + c}

x <- 1:3
do.call(example, as.list(x))
#[1] 5

However, note that this will fail if the vector is too short or too long:

但请注意,如果向量太短或太长,这将失败:

y <- 1:4
do.call(example, as.list(y))
#Error in (function (a, b, c)  : unused argument (4)