替换 R 中 SpatialPolygonsDataFrame 中的值 - 不兼容的类型

Replacing values in a SpatialPolygonsDataFrame in R - incompatible types

我正在使用 R 中的 sp 包对多边形中的点属性进行相当简单的聚合(即 SpatialPolygonsDataFrame 中的 SpatialPointsDataFrame)。我相信我可以毫无问题地做到这一点。但是,为了制作 "prettier" 图,我想用数字 0 替换没有出现点的聚合区域(使用 aggregate 函数后给定的 NA)。当我这样做时,我收到错误:

[<-.data.frame(*tmp*, i, j, value = ) 错误: 子分配类型 fix

中的不兼容类型(从 S4 到 double)

请参阅下面的可重现代码。我正在与华盛顿州合作,所以我决定继续我的示例:

library(sp)
library(raster)

### Get Washington County map ###
USCounty <- raster::getData('GADM', country='USA', level=2) # Download US County Map
WA <- USCounty[USCounty$NAME_1 == "Washington",] # Subset data to just the State of WA

### Create point data ###

# Set parameters
numPts <- 30 # Set the number of points

# Set projection I want
ptsCRS <- "+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +ellps=GRS80 +towgs84=0,0,0"

# Project data
WA <- spTransform(WA, ptsCRS)

# Create point coordinates and attribute data
set.seed(22)
x <- sample(xmin(WA):xmax(WA), numPts, replace = TRUE) #xvalues in the extent of the state
y <- sample(ymin(WA):ymax(WA), numPts, replace = TRUE) #yvalues in the extent of the state
ptsCoords <- cbind(x,y) # Store the coordinates
ptsData <- data.frame(Att = rnorm(numPts, 7, 1)) # Create and store attribute data

pts <- SpatialPointsDataFrame(ptsCoords, data = ptsData, proj4string = crs(WA))

# Plot the data
plot(WA)
plot(pts, add = TRUE)

### Perform Aggregation of point attributes by WA polygons ###
countyAgg <- aggregate(pts[WA, "Att"], WA, sum)

### Plot Data ###
spplot(countyAgg)

情节是我想要的,但是,我想将 "empty" 多边形视为数字 0。我看到 "empty" 多边形是 NAs

所以我做了:

# Find NAs
naIndex <- which(is.na(countyAgg$Att))

# Replace with zeroes
countyAgg[naIndex,]$Att <- 0

我得到错误:

incompatible types (from S4 to double) in subassignment type fix.

任何人都可以帮助我的情况,and/or 为我的问题的任何方面提供替代方法?

使用countyAgg[naIndex, "Att"] <- 0

区别可以从以下语句看出:

R> class(countyAgg[naIndex,]$Att)
[1] "numeric"
R> class(countyAgg[naIndex, "Att"])
[1] "SpatialPolygonsDataFrame"
attr(,"package")
[1] "sp"