简体   繁体   中英

R - Finding centroids of different id values

I'm trying to find the centroids for a SpatialPointsDataFrame I created. The following is a snippet of the data frame called "spdf".

    Name    X   Y
1   16  56  39
2   16  57  39
3   16  55  38
4   16  55  37
5   16  54  38
6   16  55  39
7   16  55  40
8   12  58  41
9   12  56  45
10  12  58  43
11  12  56  42
12  12  55  44
13  12  55  47

I'm using the function "gCentroid" from the "rgeos" package to identify centroids. I'm able to calculate the centroid for the entire data frame with gCentroid(spdf, byid = FALSE) but I get errors when I try to calculate centroids based on the "Name" field using gCentroid(spdf, byid = TRUE, id = "Name") . In other words, based on the above data, I'd like to get two centroids for the Names "12" and "16". The documentation on gCentroid is sparse regarding the "id" field. Does anyone have any suggestions on how I can calculate centroids for each "Name"?

The documentation is slightly confusing, but you aren't specifying the ID input, you are specifying output. Each point in your example has it's own ID (the rownames of the data frame which must by definition be unique). You can easily get your desired output however, by subsetting your data frame by the unique values in df$Name and calculating the centroids this way...

ctrs <- lapply( unique( df$Name ) , function(x) gCentroid( SpatialPoints( df[ df$Name == x , c('X','Y') ] ) ) )
setNames( ctrs , unique(df$Name ) )
#$`16`
#SpatialPoints:
#         x        y
#1 55.28571 38.57143
#Coordinate Reference System (CRS) arguments: NA 

#$`12`
#SpatialPoints:
#         x        y
#1 56.33333 43.66667
#Coordinate Reference System (CRS) arguments: NA 

ps I always thought you should be able to do this my having an object of SpatialCollections but it seems you cannot specify a list of Spatial objects of the same type (despite what the documentation for that class says).

If you're computing centroids by taking the average of the X and Y values, you can use aggregate :

aggregate(.~Name, data=dat, mean)
#   Name        X        Y
# 1   12 56.33333 43.66667
# 2   16 55.28571 38.57143

This appears to match the results from gCentroid :

library(sp)
library(rgeos)
spdf <- dat
coordinates(spdf) <- c("X", "Y")
gCentroid(spdf[spdf$Name == 12,], byid=FALSE)
# SpatialPoints:
#          x        y
# 1 56.33333 43.66667
# Coordinate Reference System (CRS) arguments: NA 
gCentroid(spdf[spdf$Name == 16,], byid=FALSE)
# SpatialPoints:
#          x        y
# 1 55.28571 38.57143
# Coordinate Reference System (CRS) arguments: NA 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM