替换空间多边形数据框中的多边形

Replace a Polygon in a Spatial Polygon Data Frame

我有一个包含多个 shapefile 的空间多边形数据框。我想通过高程 trim 这些 shapefile 并替换数据框中的原始 shapefile。但是,当我尝试替换 trim 之后的多边形时,似乎出现了错误。目前,我的计划是 运行,但对数据集中的每个 shapefile 进行以下循环。但是,当我尝试 dist[i,] <- temp3 时,出现以下错误:

match(value, lx) 错误:'match' 需要矢量参数 另外: 警告信息: 在检查名称(值)中: 尝试设置无效名称:这可能会导致以后出现问题。看到 ?make.names

有什么建议吗?

# Load spdf
dist <- rgdal::readOGR('critterDistributions.shp');

# Load elevational ranges
rangeElevation <- read.csv(file = 'elevationRanges.csv');

# Load altitude data
elevation <- raster('ETOPO1_Bed_g_geotiff.tif');

# Tidy up CRSes
crs(elevation) <- crs(dist);

# Run loop
for (i in 1:length(dist)){
  subjName <- as.character(dist@data$Species[i]);
  if (!(subjName %in% rangeElevation$?..Species_name)){
    paste0(subjName, 'does not exist in the elevational range database.');
  }
  else{
    erNameMatch <- match(subjName, rangeElevation$?..Species_name);
    temp <- raster::reclassify(elevation, rcl = c(-Inf,rangeElevation[erNameMatch,2],NA, 
                                                  rangeElevation[erNameMatch,2],rangeElevation[erNameMatch,3],1, 
                                                  rangeElevation[erNameMatch,3],Inf,NA));
    temp2 <- dist[i,];
    temp <- mask(temp, temp2);
    temp <- crop(temp, temp2);
    temp3 <- rasterToPolygons(temp, na.rm = T, dissolve = T);
    names(temp3) <- make.names(names(temp2), unique = T);
    temp3@data <- temp2@data;
    dist[i,] <- temp3; # <<<< This is the line of code that doesn't work.
  }
}

经过进一步思考,我想出了一个解决方法:启动一个列表,然后在循环后使用 rbind 将所有内容重新组合成一个对象。我仍然有兴趣找出为什么 dist[i,] <- temp3 不起作用,但至少我能够完成这项工作。

oneSPDFtoRuleThemAll <- vector(mode = "list", length = length(dist));
for (i in 1:length(dist)){
  subjName <- as.character(dist@data$Species[i]);
  if (!(subjName %in% rangeElevation$?..Species_name)){
    paste0(subjName, 'does not exist in the elevational range database.');
  }
  else{
    erNameMatch <- match(subjName, rangeElevation$?..Species_name);
    temp <- raster::reclassify(elevation, rcl = c(-Inf,rangeElevation[erNameMatch,2],NA, 
                                                  rangeElevation[erNameMatch,2],rangeElevation[erNameMatch,3],1, 
                                                  rangeElevation[erNameMatch,3],Inf,NA));
    temp2 <- dist[i,];
    temp <- mask(temp, temp2);
    temp <- crop(temp, temp2);
    temp3 <- rasterToPolygons(temp, na.rm = T, dissolve = T);
    names(temp3) <- make.names(names(temp2), unique = T);
    temp3@data <- temp2@data;
    oneSPDFtoRuleThemAll[[i]] <- temp3; # <<<< This is the line of code that doesn't work.
  }
}

finalSPDF <- rbind(unlist(oneSPDFtoRuleThemAll));