1

我正在使用包 gdistance 进行最低成本分析。这个想法是通过具有定义的成本值的成本网格(栅格)确定从目标点到源的路径;该路径因此避免了具有高成本的像素,并且更喜欢具有低成本值的像素。对我的数据有用的代码是:

Costpath<-shortestPath(CostTrans,Cherangfirstloc.utm[1,],Cherangfirstloc.utm[132,], output="SpatialLines")

因此,CostTrans构成成本网格,Cherangfirstloc.utm[1,]是来自 Spatialpoints 数据帧(源)Cherangfirstloc.utm[132,]的第一个位置/点,是来自 Spatialpoints 数据帧(目的地)的最后一个位置/点。输出是连接两个位置/点的线。

但是,我现在想计算多个最小成本路径,因此源应该是数据帧的每一行,目标保持不变。这意味着下一个来源将是Cherangfirstloc.utm[2,], thenCherangfirstloc.utm[3,]等等。我认为这可以通过 for 循环或sapply函数来完成。不幸的是,我不知道如何制定这个。

你能给我一些关于如何制定这个迭代过程的提示吗? 如果我在这个地方问这个问题,我希望没关系。基本上,我只想知道如何遍历数据框。因此,gdistance 和最低成本分析如何工作并不重要。

以下是一些可用作示例数据的代码:

library(gdistance)

r <- raster(nrows=6, ncols=7, xmn=0, xmx=7, ymn=0, ymx=6, crs="+proj=utm 
+units=m")

r[] <- c(2, 2, 1, 1, 5, 5, 5, #creates costgrid
 2, 2, 8, 8, 5, 2, 1,
 7, 1, 1, 8, 2, 2, 2,
 8, 7, 8, 8, 8, 8, 5,
 8, 8, 1, 1, 5, 3, 9,
 8, 1, 1, 2, 5, 3, 9)

T <- transition(r, function(x) 1/mean(x), 8) #creates transition layer of costgrid
T <- geoCorrection(T) #correction

c1 <- c(5.5,1.5) #first source point
c2 <- c(5.5,4) #second source point
c3 <- c(1.5,5.5) #destination

sPath2 <- shortestPath(T, c1, c3, output="SpatialLines") # creates the least cost path

不幸的是,我不知道如何在 Spatialpoints 数据框中包含 c1、c2 和 c3,以便可以迭代。希望这仍然有帮助。

如果您能给我任何提示,我将不胜感激。感谢您的努力!

4

1 回答 1

2

如果您只想shortestPath使用不同的参数调用函数,最简单的解决方案是使用for如下所示的循环。由于我不熟悉这种分析,我不知道你想对结果做什么,所以这里有两个解决方案:

在此示例中,您将立即使用最短路径,因为它会在下一步被遗忘:

for(i in 1:nrow(Cherangfirstloc.utm)) {
  # Computation
  Costpath <- shortestPath(CostTrans, Cherangfirstloc.utm[i,], Cherangfirstloc.utm[132,], output="SpatialLines") 

  ### Here your instructions for a direct use of the result ###
}

在这一个中,所有路径都将存储在一个列表中(似乎该shortestPath函数返回一个对象,因此它是更方便的存储方式),每个结果都可以在results变量中访问,例如results[[12]]从第 12 行开始的路径:

results = list()
for(i in 1:nrow(Cherangfirstloc.utm)) {
  # Computation, storage in a list element
  results[[i]] <- shortestPath(CostTrans, Cherangfirstloc.utm[i,], Cherangfirstloc.utm[132,], output="SpatialLines") 
}

### Here your instructions for a global use of the result ###
于 2011-11-15T10:18:52.840 回答