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

时间:2019-10-07 10:24:38

标签: r gis

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

match(value,lx)中的错误:“ match”需要向量参数 另外:警告消息: 在checkNames(value)中:   尝试设置无效名称:稍后可能会导致问题。请参阅?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.
  }
}

1 个答案:

答案 0 :(得分:0)

经进一步思考,我想出了一种解决方法:启动一个列表,然后在循环后使用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));
相关问题