【问题标题】:How to simplify FOR loops in R?如何简化 R 中的 FOR 循环?
【发布时间】:2015-01-20 21:06:33
【问题描述】:
for(i in 1:100)
{
  for(j in 1:100)
  {
       hdist <- rgeos::gDistance(xySpatialLines[[i]], xySpatialLines[[j]], byid=FALSE, hausdorff=TRUE)
       distances[i,j] <- dist 
  }
}

有什么办法可以简化 j 循环得到这样的东西:

for(i in 1:100)
{
  distances[i,j] <- lapply(???)  # or sapply?
}

更新:

xySpatialLines[[i]] 中存储的数据 - 这些是 SpatialLines 对象:

library(sp)
xySpatialLines <- vector(mode = "list", length = 2)
x1 <- c(1,4,5,3,2)
y1 <- c(2,5,3,6,7)
x2 <- c(4,4,6,3,2)
y2 <- c(8,5,2,6,1)
xy1 <- cbind(x1,y1)
xy2 <- cbind(x2,y2)
xy1.sp = sp::SpatialPoints(xy1)
xy2.sp = sp::SpatialPoints(xy2)
spl1 <- sp::SpatialLines(list(Lines(Line(xy1.sp), ID="a")))
spl2 <- sp::SpatialLines(list(Lines(Line(xy2.sp), ID="b")))
xySpatialLines[[1]] = spl1
xySpatialLines[[2]] = spl2

【问题讨论】:

  • 看看mapply(多变量lapply)。而且你总是可以使用双 lapply()
  • @Richard Scriven:我的想法是将这个双循环转换为 foreach () %dopar% { #...mapply } O 你建议使用双 lapply 吗?我正在寻找计算效率高的解决方案
  • @Richard Scriven:请查看更新

标签: r for-loop lapply simplify sapply


【解决方案1】:

你可以使用外部:

distances = outer(xySpatialLines, xySpatialLines, FUN = gDistance, byid=FALSE, hausdorff = TRUE)

【讨论】:

  • 你的意思是这个单行会代替我的整个双循环吗?
  • 应该的。我没有来自您的问题的样本数据来确认
  • 如果您尝试一些简单的示例,例如outer(c(1,2,3), c(4,5,6), "+")outer(c(1,2,3), c(4,5,6), function(x,y) x^2 - y)outer(c(1,2,3), c(4,5,6), function(x,y) paste(x, "is less than", y)),您可以看到outer 正在做什么。
  • @Señor O:我将 SpatialLines 对象存储在向量 xySpatialLines 中
  • @Ricky -- 一切 都可以解密,可以这么说。这可能需要更多步骤,但当然可以完成。
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-10
  • 1970-01-01
  • 2020-01-14
  • 2018-04-11
  • 2016-03-06
相关资源
最近更新 更多