大家好,我希望我能在这个问题上得到一些帮助:
我有一个包含2347个特征的shapefile,对应于3172个单元,也许在创建原始文件时,有一些重复的几何图形,他们决定这样排列它们:
Feature gis_id
1 "1"
2 "2"
3 "3,4,5"
4 "6,8"
5 "7"
6 "9,10,13" ..。就像这样直到3172个单元和2347个特征
另一方面,我的数据表有72956个观察值(大约16列),其中的数据对应于shapefile中的gis_id。但是,此表的每个观察值都有唯一的gis_id
head(hru_ls)
jday mon day yr unit gis_id name sedyld tha sedorgn kgha sedorgp kgha surqno3 kgha lat3no3 kgha
1 365 12 31 1993 1 1 hru0001 0.065 0.861 0.171 0.095 0
2 365 12 31 1993 2 2 hru0002 0.111 1.423 0.122 0.233 0
3 365 12 31 1993 3 3 hru0003 0.024 0.186 0.016 0.071 0
4 365 12 31 1993 4 4 hru0004 6.686 16.298 1.040 0.012 0
5 365 12 31 1993 5 5 hru0005 37.220 114.683 6.740 0.191 0
6 365 12 31 1993 6 6 hru0006 6.597 30.949 1.856 0.021 0
surqsolp kgha usle tons sedmin ---- tileno3 ----
1 0.137 0 0.010 0
2 0.041 0 0.009 0
3 0.014 0 0.001 0
4 0.000 0 0.175 0
5 0.000 0 0.700 0
6 0.000 0 0.227 0每个单元有多个记录(20年数据)
我想将shapefile的几何数据合并到我的数据表中。我以前用sp::merge做过这件事,但shapefile的每个几何形状/特征没有多个id。
有没有一种方法可以调整合并的条件,使其根据是否具有shapefile中gis_id字段上的任何值来为数据表中的每个要素提供相应的几何图形?
发布于 2021-08-27 12:50:11
这是一个非常耐人寻味的问题,所以我试了试。我的答案可能不是最快或最简洁的方法,但它是有效的(至少对于您的样本数据)。注意,这种方法对shapefile$gis_id中的数据格式化相当敏感(请参阅正则表达式)。
# your spatial data
shapefile <- data.frame(feature = 1:6, gis_id = c("1", "2", "3,4,5", "6,8", "7", "9,10,13"))
# your tabular data
hru_ls <- data.frame(unit = 1:6, gis_id = paste(1:6))
# loop over all gis_ids in your tabular data
# perhaps this could be vectorized?
gis_ids <- unique(hru_ls$gis_id)
for(id in gis_ids){
# Define regex to match gis_ids
id_regex <- paste0("(,|^)", id, "(,|$)")
# Get row in shapefile that matches regex
searchterm <- lapply(shapefile$gis_id, function(x) grepl(pattern = id_regex, x = x))
rowmatch <- which(searchterm == TRUE)
# Return shapefile feature id that maches tabular gis_id
hru_ls[hru_ls$gis_id == id, "gis_feature_id"] <- shapefile[rowmatch, "feature"]
}因为您没有在问题中提供几何字段,所以我只是在您的空间数据中匹配了Feature。可以添加基于Feature合并的附加步骤,也可以使用几何体字段替换shapefile[rowmatch, "feature"]中的"feature"。
https://stackoverflow.com/questions/68654477
复制相似问题