简体   繁体   English

R中是否有一些“交叉应用”功能?

[英]Is there some 'cross apply' function in R?

Is there some function in R of the form like: 在表格的R中是否有一些功能如:

crossApply(v1, v2, func)

that has the same functionality as: 具有相同的功能:

ret = c()
i = 1
for (e1 in v1) {
  for (e2 in v2) {
    ret[i] <- func(e1,e2)
    i <- i + 1
  }
}
return(ret)

Thanks in advance. 提前致谢。

I think you may be looking for outer which isn't exactly what your code does, but it's close. 我认为你可能正在寻找outer ,这不是你的代码所做的,但它很接近。 Specifically, outer will return the matrix (ie the outer product) or each combination of the elements of its first two arguments. 具体而言, outer将返回矩阵(即外部产品)或其前两个参数的元素的每个组合。

You'd probably want to store the result and then extract the lower triangle as a vector. 您可能希望存储结果,然后将下三角形提取为矢量。 Something like this maybe: 这样的事情可能是:

rs <- outer(1:4,-(5:7),"+")
rs[lower.tri(rs,diag = TRUE)]
[1] -4 -3 -2 -1 -4 -3 -2 -4 -3

An example 一个例子

func <- function(x,y) {sqrt(x^2+y^2)}
v1 <- c(1,3,5)
v2 <- c(0,-4,-12)
ret <- outer(v1,v2,"func")

And you then have 然后你就拥有了

> ret
     [,1]     [,2]     [,3]
[1,]    1 4.123106 12.04159
[2,]    3 5.000000 12.36932
[3,]    5 6.403124 13.00000

or if you want exactly what your for loops would produce 或者如果你想要你的for循环会产生什么

> as.vector(t(ret))
[1]  1.000000  4.123106 12.041595  3.000000  5.000000 12.369317  5.000000
[8]  6.403124 13.000000

It's fairly easy to do with do.call and expand.grid : 使用do.callexpand.grid相当容易:

x <- seq(0,10, length.out=10)
> y <- seq(-1,1, length.out=5)
> d1 <- expand.grid(x=x, y=y)  
> do.call("*", d1)
 [1]   0.0000000  -1.1111111  -2.2222222  -3.3333333  -4.4444444
 [6]  -5.5555556  -6.6666667  -7.7777778  -8.8888889 -10.0000000
[11]   0.0000000  -0.5555556  -1.1111111  -1.6666667  -2.2222222
[16]  -2.7777778  -3.3333333  -3.8888889  -4.4444444  -5.0000000
[21]   0.0000000   0.0000000   0.0000000   0.0000000   0.0000000
[26]   0.0000000   0.0000000   0.0000000   0.0000000   0.0000000
[31]   0.0000000   0.5555556   1.1111111   1.6666667   2.2222222
[36]   2.7777778   3.3333333   3.8888889   4.4444444   5.0000000
[41]   0.0000000   1.1111111   2.2222222   3.3333333   4.4444444
[46]   5.5555556   6.6666667   7.7777778   8.8888889  10.0000000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM