【发布时间】: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