如何简化R中的FOR循环?

如何简化R中的FOR循环?,r,for-loop,lapply,simplify,sapply,R,For Loop,Lapply,Simplify,Sapply,您可以使用: 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 = s

您可以使用:

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
您可以使用:

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

查看
mappy
(多元
lappy
)。你总是可以使用double
lappy()
@Richard Scriven:我的想法是将这个双循环转换成foreach()%dopar%{#…mapply}O你建议使用double-lappy吗?我正在寻找计算效率高的方法solution@RichardScriven:请查看更新查看
mapply
(多维
Lappy
)。你总是可以使用double
lappy()
@Richard Scriven:我的想法是将这个双循环转换成foreach()%dopar%{#…mapply}O你建议使用double-lappy吗?我正在寻找计算效率高的方法solution@Richard斯克里文:请看更新版。你是说这一行将取代我的整个双环吗?应该是这样的。我没有你问题中的样本数据可以证实,如果你尝试一些简单的例子,比如
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,“小于”,y))你可以看到
outer(c(1,2,5,3),c(4,5,6),c(4,5,6),c(4,5,5,6),x,y)的作用
@Señor O:I将空间线对象存储在向量中xySpatialLines@Ricky可以说,任何东西都可以去分类。这可能需要更多的步骤,但当然可以做到。你的意思是这一条线将取代我的整个双环吗?它应该。我没有你问题中的样本数据可以证实,如果你尝试一些简单的例子,比如
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,“小于”,y))你可以看到
outer(c(1,2,5,3),c(4,5,6),c(4,5,6),c(4,5,5,6),x,y)的作用
@Señor O:I将空间线对象存储在向量中xySpatialLines@Ricky可以说,任何东西都可以去分类。这可能需要更多的步骤,但当然可以做到。
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
distances = outer(xySpatialLines, xySpatialLines, FUN = gDistance, byid=FALSE, hausdorff = TRUE)