【发布时间】:2014-07-27 20:07:35
【问题描述】:
我正在处理间隔,我希望有一种有效的方法来找到每个间隔之间的距离。距离函数都采用两个二维向量。我需要将每一行与 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() 工作,我也会很好。任何可以加快我可耻的 for 循环的方法!
【问题讨论】:
-
您应该知道
apply通常不会比(写得好)for 循环快很多。 -
和
Vectorize只隐藏mapply。
标签: r for-loop performance outer-join