R:分别对两个变量的每个元素应用一个函数 [英] R: apply a function to every element of two variables respectively
问题描述
我有一个带有两个变量 x 和 y 的函数:
I have a function with two variables x and y:
fun1 <- function(x,y) {
z <- x+y
return(z)
}
该函数本身工作正常:
fun1(15,20)
但是当我尝试将它与 x 和 y 的两个向量与应用函数一起使用时,我没有得到正确的 56*121 数组
But when I try to use it with two vectors for x and y with an apply function I do not get the correct 56*121 array
Lx <- c(1:56)
Ly <- c(1:121)
mapply(fun1, Lx, Ly)
我将非常感谢您的帮助以及有关最快解决方案的建议(例如,data.table 或 dplyr 解决方案比应用更快).
I would be grateful for your help and also on advice on the fastest solution (eg is a data.table or dplyr solution faster than apply).
推荐答案
如果你想使用 mapply()
你必须为它提供 n 个具有相同大小的参数列表,这将被 n 个 n 传递给函数,如:
If you want to use mapply()
you have to provide it with n lists of arguments that have same size, and that will be passed to the function n by n, as in:
mapply(fun1,c(1,2,3), c(4, 5, 6))
[1] 5 7 9
或者一个参数可以是一个标量,如:
or one argument can be a scalar as in:
mapply(fun1,c(1,2,3), 4)
[1] 5 6 7
由于您尝试使用 Lx
和 Ly
的所有组合,您可以迭代一个列表,然后迭代另一个列表,例如:
Since you're trying to use all combinations of Lx
and Ly
, you can iterate one list, then iterate the other, like:
sapply(Lx, function(x) mapply(fun1,x,Ly))
或
sapply(Ly, function(y) mapply(fun1,Lx,y))
产生与 rawr 命题相同的结果
which produces same result as rawr proposition
outer(Lx, Ly, fun1)
其中 outer()
更快
这篇关于R:分别对两个变量的每个元素应用一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!