[英]How to group repeating sequences of numbers using R
我想要做的最簡單的描述是,我在data.frame中有一列,例如1,2,3,..., n, 1,2,3,...n,....
和我想將第一個1 ... n分組為1,第二個1 ... n分組為2,依此類推。
完整的上下文是; 我正在使用R spcosa
軟件包對一塊土地進行等面積分層復合采樣。 我首先從GIS中的形狀文件開始,該文件包含許多多邊形(地塊)。 我想要的最終結果是一個GIS文件,其中包含每個地層和樣本位置,且格式為GIS文件格式,每個地層和樣本位置均以地塊,地層和樣本ID標記。 到目前為止,我可以完成所有這一切,除了一位可以識別樣本所屬的層次並將其包括在樣本標簽中之外。 樣本標簽的外觀應類似於“ parcel#-strata#-composite#(其中#是數字)。實際上,我不需要此實際標簽,而是在GIS文件中作為單獨的屬性使用。
基本工作流程如下
對於使用spcosa :: stratify的每個單獨的多邊形,我將其划分為多個等面積的地層,例如
strata.CSEA <- stratify(poly[i,], nStrata = n, nTry = 1, equalArea = TRUE, nGridCells = x)
注意spcosa::stratify
生成一個CompactStratificationEqualArea
對象。 我將其SpatialPixelData
設置為SpatialPixelData
然后使用rasterToPolygon
將其輸出為GIS文件。
然后,我將生成示例位置,如下所示:
samples.SPRC <- spsample(strata.CSEA, n = n, type = "composite")
spcosa::spsample
創建一個SamplingPatternRandomComposite
對象。 我強迫這個到SpatialPointsDataFrame
samples.SPDF <- as(samples.SPRC, "SpatialPointsDataFrame")
並將兩列添加到@data插槽
samples.SPDF@data$Strata <- "this is the bit I can't do yet"
samples.SPDF@data$CEA <- poly[i,]$name
然后,我可以寫samples.SPDF
作為GIS文件(即writeOGE)與所有想要的屬性。
如上所述,我無法弄清樣本ID與分層ID的關系。 采樣點是一個像1,2,3...n, 1,2,3...n,....
的向量。 由於實際層數是任意的,因此我可以將其分組(根據上面的簡單問題),但理想情況下,我想使用實際層數來進行排列。
為了使所有貢獻者都能接觸到示例,我在下面略微修改了spcosa文檔中的代碼,以生成正確的對象。
# Note: the example below requires the 'rgdal'-package You may consider the 'maptools'-package as an alternative
if (require(rgdal)) {
# read a vector representation of the `Farmsum' field
shpFarmsum <- readOGR(
dsn = system.file("maps", package = "spcosa"),
layer = "farmsum"
)
# stratify `Farmsum' into 50 strata
# NB: increase argument 'nTry' to get better results
set.seed(314)
myStratification <- stratify(shpFarmsum, nStrata = 50, nTry = 1, equalArea = TRUE)
# sample two sampling units per stratum
mySamplingPattern <- spsample(myStratification, n = 2 type = "composite")
# plot the resulting sampling pattern on
# top of the stratification
plot(myStratification, mySamplingPattern)
}
也許order()函數可以為您提供幫助
n <- 10
dat <- data.frame(col1 = rep(1:n, 2), col2 = rnorm(2*n))
head(dat)
dat[order(dat$col1), ]
我沒有找到“ ID”( 1,2,3...n
)的位置; 因此,假設您有SpatialPolygonsDataFrame
名為shpFarmsum
,其屬性數據shpFarmsum
“ ID”。 您可以通過shpFarmsum$ID
訪問此列。 因此,如果要為每個ID創建單獨的子集,這是一種方法:
for (i in unique(shpFarmsum$ID)) {
tempSubset shpFarmsum[shpFarmsum$ID == i,]
writeOGR(tempSubset, ".", paste0("subset_", i), driver = "ESRI Shapefile")
}
我添加了一行writeOGR(...
因此所有子集都寫入到您的工作目錄中。但是,您可以更改此行或將進一步的分析添加到for循環中。
這個怎么運作
unique(shpFarmsum$ID)
提取所有出現的ID(與您的1,2,3...n
)。
在for循環的每次重復中,此ID的另一個值將用於創建整個SpatialPolygonsDataFrame
的子集,您可以將其用於進一步分析。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.