Spatialpolygonsdataframe:基于其他列的聚合而不将其转换为数据框?在 r

Spatialpolygonsdataframe: aggregation based on other columns without turning it into data frame ? in r

我有一个空间多边形数据框。我想根据几列汇总列死亡人数。

我应用了以下代码:

sp = aggregate(fatalities~gid+year+event_type+xcoord+ycoord+country, test2@data, sum)

但我不希望我的 sp 变成数据框。如何将其保留为空间对象?

这是我的数据:

dput(head(test2, 10))

structure(list(id = c(1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), 
    gid = c("183253", "183254", "183254", "183254", "183254", 
    "183254", "183254", "183254", "183254", "183254"), xcoord = c(6.25, 
    6.75, 6.75, 6.75, 6.75, 6.75, 6.75, 6.75, 6.75, 6.75), ycoord = c(37.25, 
    37.25, 37.25, 37.25, 37.25, 37.25, 37.25, 37.25, 37.25, 37.25
    ), col = c("373", "374", "374", "374", "374", "374", "374", 
    "374", "374", "374"), row = c("255", "255", "255", "255", 
    "255", "255", "255", "255", "255", "255"), gwno = c(615L, 
    615L, 615L, 615L, 615L, 615L, 615L, 615L, 615L, 615L), country = c("Algeria", 
    "Algeria", "Algeria", "Algeria", "Algeria", "Algeria", "Algeria", 
    "Algeria", "Algeria", "Algeria"), km2 = c(3875.43674549, 
    3875.43674549, 3875.43674549, 3875.43674549, 3875.43674549, 
    3875.43674549, 3875.43674549, 3875.43674549, 3875.43674549, 
    3875.43674549), year = c(0, 2000, 2001, 2002, 2003, 2003, 
    2005, 2006, 2006, 2007), event_type = c("0", "Battles", "Battles", 
    "Strategic developments", "Riots", "Battles", "Battles", 
    "Violence against civilians", "Battles", "Explosions/Remote violence"
    ), longitude = c(0, 6.572, 6.572, 6.572, 6.572, 6.572, 6.572, 
    6.514, 6.572, 6.572), latitude = c(0, 37.006, 37.006, 37.006, 
    37.006, 37.006, 37.006, 37.002, 37.006, 37.006), fatalities = c(0, 
    8, 7, 0, 0, 1, 1, 0, 5, 0), Incidence = c(0, 1, 1, 0, 0, 
    1, 1, 0, 1, 0), LagIncidenceYear = c(0, 0, 1, 1, 0, 0, 1, 
    1, 0, 1), Onset = c(0, 1, 0, 0, 0, 1, 0, 0, 1, 0)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -10L), groups = structure(list(
    gid = c("183253", "183254"), .rows = structure(list(1L, 2:10), ptype = integer(0), class = c("vctrs_list_of", 
    "vctrs_vctr", "list"))), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -2L), .drop = TRUE))

您可以使用变量名来聚合多边形

library(raster)
p <- shapefile(system.file("external/lux.shp", package="raster"))
p0 <- aggregate(p, c("ID_1", "NAME_1"))

然后添加你想要的属性

x <- aggregate(ID_2 ~ NAME_1, p@data, FUN=mean)
px <- merge(p0, x)

px
#class       : SpatialPolygonsDataFrame 
#features    : 3 
#extent      : 5.74414, 6.528252, 49.44781, 50.18162  (xmin, xmax, ymin, ymax)
#crs         : +proj=longlat +datum=WGS84 +no_defs 
#variables   : 3
#names       :     NAME_1, ID_1, ID_2 
#min values  :   Diekirch,    1,    3 
#max values  : Luxembourg,    3,  9.5