繁体   English   中英

我可以对二维向量使用external()或apply()函数吗?

[英]Can I use the outer() or apply() function with 2-dimensional vectors?

我正在使用间隔,并且我想采用一种有效的方法来查找每个间隔之间的距离。 距离函数全部采用两个二维向量。 我需要将每一行与nx2数据帧中的每一行相对。

这是我现在拥有的代码(inside distance只是一个示例函数,但是所有函数都使用相同的输入):

# Inside takes vectors I1 and I2
inside <- function(I1, I2) min(I1[1]-I2[2], I2[1]-I1[2])
# the example intervals are (0,1), (1,2), and (4,5).
I <- data.frame(l=c(0,1,4), u=c(1,2,5))
n <- nrow(I)

d <- matrix(rep(NA, n^2), nrow=n)
# I'm ashamed that I wrote nested for loops (I have no programming training)
for(i in 1:n){
    for(j in 1:n){
        d[i,j] <- inside(I[i,],I[j,])
    }
}

这是模拟研究的一部分,因此该代码必须运行数千次。 由于它使用嵌套的for循环,因此效率低下。 这是我要使用的代码:

index <- 1:nrow(I)
d <- outer(index, index, function(x, y) inside(I[x,], I[y,]))

如果该代码有效,我就不会在这里寻求您的帮助。

如果我能以某种方式使apply()工作,也可以。 加快我可耻的循环的速度!

首先,创建inside的矢量化版本:

vecInside <- Vectorize(function(x, y) inside(I[x, ], I[y, ]))   

其次,在外部使用此功能:

outer(index, index, vecInside)

结果:

     [,1] [,2] [,3]
[1,]   -1   -2   -5
[2,]   -2   -1   -4
[3,]   -5   -4   -1

v_outer功能(矢量outer的) qdaTools适用于这种任务:

library(qdapTools)
v_outer(t(I), inside)

##    V1 V2 V3
## V1 -1 -2 -5
## V2 -2 -1 -4
## V3 -5 -4 -1

暂无
暂无

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

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