SpatialPoints 和 SpatialPointsDataFrame 对象都是 S4 对象。确实,主要的结构区别在于,在后者中,有一个包含属性数据的额外槽。但实际差异更为显着。仅举几个例子(使用 sp 包中的内置 meuse 数据库,其中包含来自默兹河洪泛区的地理编码污染物数据)。
library(sp)
data(meuse)
class(meuse) # a data.frame
# [1] "data.frame"
head(meuse[,1:5]) # first 5 columns
# x y cadmium copper lead
# 1 181072 333611 11.7 85 299
# 2 181025 333558 8.6 81 277
# 3 181165 333537 6.5 68 199
# 4 181298 333484 2.6 81 116
# 5 181307 333330 2.8 48 117
# 6 181390 333260 3.0 61 137
coordinates(meuse) <- 1:2 # convert to spDF object; use first 2 columns for lon/lat
class(meuse) # now a SpatialPointsDataFrame
# [1] "SpatialPointsDataFrame"
# attr(,"package")
# [1] "sp"
即使meuse 是一个 SpatialPointsDataFrame,我们仍然可以将它作为一个简单的 data.frame 进行索引。请注意我们如何引用属性表的lead 列,就好像meuse 是一个df,并注意索引是如何像在df 中一样工作的。
meuse[meuse$lead>500,1:5] # high lead
# coordinates cadmium copper lead zinc elev
# 55 (179973, 332255) 12.0 117 654 1839 7.90
# 60 (180100, 332213) 10.9 90 541 1571 6.68
meuse[meuse$lead<40,1:5] # low lead
# coordinates cadmium copper lead zinc elev
# 112 (180328, 331158) 0.4 20 39 113 9.717
# 161 (180201, 331160) 0.8 18 37 126 9.036
我们也可以使用 SpatialPointsDataFrames 的 plot 方法来绘制数据。
par(mfrow=c(1,2), mar=c(2,2,2,2)) # 1 X 2 grid of plots; remove margins
plot(meuse, pch=20, main="Full Dataset", axes=TRUE)
plot(meuse,
bg=rev(heat.colors(5))[cut(meuse$lead,breaks=c(0,100,200,300,400,Inf),labels=FALSE)],
col="grey",main="Lead Distribution", pch=21, axes=TRUE)
我们可以将坐标转换成更有用的东西(经度/纬度)。
library(rgdal)
proj4string(meuse) <- CRS("+init=epsg:28992") # set original projection
meuse <- spTransform(meuse, CRS("+proj=longlat +datum=WGS84")) # transform to lon/lat
plot(meuse, pch=20, main="Full Dataset", axes=TRUE)
plot(meuse,
bg=rev(heat.colors(5))[cut(meuse$lead,breaks=c(0,100,200,300,400,Inf),labels=FALSE)],
col="grey",main="Lead Distribution", pch=21, axes=TRUE)
最后是一个反例,将点叠加到谷歌地图上:
library(ggmap) # loads ggplot2 as well
map <- get_map(location=rowMeans(bbox(meuse)), zoom=13) # get Google map
ggmap(map) +
geom_point(data=as.data.frame(meuse), aes(x,y,fill=lead),
color="grey70", size=3.5, shape=21)+
scale_fill_gradientn(colours=rev(heat.colors(5)))
本质上,我们在这里所做的是将meuse 从data.frame 转换为spatialPointsDataFrame,以便我们可以在坐标上使用spTransform(...),然后将结果转换回data.frame,这样我们可以使用ggplot 将它们叠加到谷歌地图上。