基本上,我試圖在 shapefile 的 polgons 內創建 5 個隨機空間點。我試圖st_sample()從sf包中使用,但我的for回圈有問題。
例子:
library(terra)
library(sf)
#10 polygons
v <- vect(system.file("ex/lux.shp", package="terra"))
v <- v[c(1:10)]
#Empty list to store values
empty_list <- list()
#for loop
for(i in 1:length(v$ID_1)){
empty_list[i] <- st_sample(x = v[i,], size = 5,
type = "random", exact =T, by_polygon = T)
}
這個回圈看起來相當簡單明了。我認為問題是st_sample()每次迭代只存盤 1 個值。我應該使用串列以外的其他東西來存盤輸出值,還是for回圈不是這里的正確選項?
uj5u.com熱心網友回復:
無需執行for回圈。您只需要為函式的size引數指定一個向量st_sample()。
我不知道你為什么要從 a 開始,SpatVector但我也給了你將物件轉換為sf類物件的代碼,因為該st_sample()函式需要一個sf或sfc類物件
所以請找到下面的reprex。
正品
- 代碼
library(terra)
library(sf)
# Convert 'SpatVector' into 'sf' object
v_sf <- st_as_sf(v)
# Create the random points (here, 5 random points for each polygon)
set.seed(452)
points <- st_sample(v_sf, size = c(5,5), type = "random")
- 輸出
plot(st_geometry(v_sf))
plot(points, pch = 20, add= TRUE)

由reprex 包(v2.0.1)于 2021 年 11 月 23 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/364172.html
上一篇:當滿足for回圈中的條件時,將行中的值附加到同一行但在新列中
下一篇:使用for回圈在R中抓取網頁
