我试图为我创建的SpatialPointsDataFrame找到质心。下面是名为"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我使用"rgeos“包中的函数"gCentroid”来识别质心。我能够用gCentroid(spdf, byid = FALSE)计算整个数据帧的质心,但是当我试图使用gCentroid(spdf, byid = TRUE, id = "Name")根据"Name“字段计算质心时会出现错误。换句话说,根据上面的数据,我想得到两个名为"12“和"16”的质心。关于gCentroid的文档很少涉及"id“字段。有人对我如何计算每一个“名字”的质心有什么建议吗?
发布于 2014-04-28 22:27:33
文档有点混乱,但您没有指定ID输入,而是指定了输出。示例中的每个点都有自己的ID (数据帧的行名,根据定义,它必须是唯一的)。但是,您可以很容易地获得您想要的输出,方法是用df$Name中的唯一值来设置数据帧,并以这种方式计算质心.
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 附注:我一直认为您应该能够这样做--我有一个SpatialCollections对象--但是似乎您不能指定相同类型的空间对象的list (不管该类的文档中说了什么)。
发布于 2014-04-28 22:00:39
如果通过取X值和Y值的平均值来计算质心,则可以使用aggregate
aggregate(.~Name, data=dat, mean)
# Name X Y
# 1 12 56.33333 43.66667
# 2 16 55.28571 38.57143这似乎与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 https://stackoverflow.com/questions/23351743
复制相似问题