2011-11-14 34 views
1

我正在使用软件包gdistance进行最低成本分析。 这个想法是通过costgrid(栅格)来确定从目标点到源的路径,并且具有已定义的成本值;因此路径避免了高成本的像素并且优选具有低成本值的像素。与我的数据对我的作品的代码是:循环或sapply函数用于R中的多个最小成本分析

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

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

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

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

下面是一些代码,可以作为样本数据:

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 

不幸的是,我不知道如何将C1,在Spatialpoints数据帧C2和C3,使人们可以遍历。希望这仍然有帮助。

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

回答

1

如果您只是想用变化的参数调用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 ### 
+0

太棒了,这是完美的作品。非常感谢您的帮助! –