【问题标题】:Can I use the outer() or apply() function with 2-dimensional vectors?我可以将 external() 或 apply() 函数与二维向量一起使用吗?
【发布时间】: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


【解决方案1】:

首先,创建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

【讨论】:

  • 谢谢!我只是想通了。我假设 outer() 像 apply() 一样工作并接受自定义标量函数。它仍然不是很快,但速度要快得多!
【解决方案2】:

qdaTools 中的 v_outer 函数(矢量化 outer)适用于此类任务:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多