我正在尝试生成随机形状和大小的图,这些图将覆盖光栅图像的 85%。到目前为止,这是我所拥有的,但我不断收到错误消息。我已经尝试了很多不同的迭代,但消息仍然存在。如果有人能找到错误,我将不胜感激。
错误(函数(类,fdef,mtable): 无法找到函数“proj4string<-’ for signature ‘"Polygon", "CRS"’
”的继承方法library(sp)
library(ggplot2)
library(rgeos)
library(sf)
library(rgdal)
library(raster)
# image
site <- raster("C:/Users/ichth/OneDrive/Documents/Restoration_Implementation/Design_Project/Site_Raster.tif")
# plot size min/max in pixels
plot_size <- c(10, 25)
# find raster total area
total_area <- cellStats(site, sum)
# find area needed to cover 85%
target_area <- 0.85 * total_area
# create empty data frame
plots <- SpatialPolygonsDataFrame(
SpatialPolygons(list()),
data.frame(id = numeric(), area = numeric(), row.names = character()),
match.ID = FALSE
)
# loop until target reached
while (sum(plots$area) < target_area) {
# next plot random location and size
x <- runif(1, xmin(site), xmax(site))
y <- runif(1, ymin(site), ymax(site))
size <- runif(1, plot_size[1], plot_size[2])
# set coordinate system for plots
crs(site) <- "+proj=tmerc +lat_0=24.3333333333333 +lon_0=-81 +k=0.999941177 +x_0=200000.0001016 +y_0=0 +datum=NAD83 +units=us-ft +no_defs"
# create overall polygon
pol <- Polygon(
matrix(
c(x, x + size, x + size, x, x,
y, y, y + size, y + size, y),
ncol = 2, byrow = TRUE))
# set coordinate system for plots
proj4string(pol) <- CRS(as.character(crs(site)))
# add to plots data frame
spatial_poly <- SpatialPolygons(list(Polygons(list(pol), ID = as.character(length(plots) + 1))))
plots <- rbind(plots, data.frame(id = length(plots) + 1, area = gArea(pol), row.names = as.character(length(plots) + 1)))
coordinates(plots) <- c("x", "y")
# check if target area has been reached
if (sum(plots$area) >= target_area) {
break
}
# plot on raster
ggplot() +
geom_raster(data = as.data.frame(site), aes(x = x, y = y, fill = value)) +
geom_polygon(data = as.data.frame(plots), aes(x = x, y = y, fill = area), color = "white", alpha = 0.7) +
coord_equal() +
theme_void() +
scale_fill_gradient(low = "white", high = "red")
}
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘proj4string<-’ for signature ‘"Polygon", "CRS"’
Polygon
对象是纯几何的,没有坐标参考。因此,我认为导致您的错误消息的最小说明是:
> pol = Polygon(coords=cbind(c(0,1,1,0,0), c(0,0,1,1,0)))
> proj4string(pol)=CRS("+init=epsg:4326")
Error in (function (classes, fdef, mtable) :
unable to find an inherited method for function ‘proj4string<-’ for signature ‘"Polygon", "CRS"’
>
SpatialPolygons
确实有坐标系,您已经编写了代码来构造它,所以我假设您知道如何为您的数据执行此操作。这是我如何用我的例子来做的:
> spol = SpatialPolygons(list(Polygons(list(pol),ID=1)))
> proj4string(spol)=CRS("+init=epsg:4326")
你可以在一行中用一个额外的参数来做到这一点
SpatialPolygons
:
> spol = SpatialPolygons(
list(Polygons(list(pol),ID=1)),
proj4string=CRS("+init=epsg:4326")
)
>