2011-11-14 53 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

太棒了,這是完美的作品。非常感謝您的幫助! –