我有一个跨越整个地球的数据点CSV(the US Geological Service's earthquake feed),我想只过滤美国境内的地震'边界。
我从美国人口普查局撤下的KML文件:
https://www.census.gov/geo/maps-data/data/kml/kml_nation.html
在R中,rgdal
库可以加载KML文件:
library(rgdal)
kml = readOGR("kmls/cb_2014_us_nation_20m.kml", 'cb_2014_us_nation_20m')
如何使用dplyr
/ plyr
/等。过滤data.frame(地理数据的列是latitude
和longitude
)仅针对属于KML指定的边界内的行?
编辑,回复后:
以下是@hrbrmstr's answer用于快速展示的内容:
library(sp)
library(rgdal)
# download earthquakes
url <- "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.csv"
fil <- "all_week.csv"
if (!file.exists(fil)) download.file(url, fil)
quakes <- read.csv("all_week.csv", stringsAsFactors=FALSE)
# create spatial object
sp::coordinates(quakes) <- ~longitude+latitude
# download nation KML
url <- "http://www2.census.gov/geo/tiger/GENZ2014/kml/cb_2014_us_nation_20m.zip"
fil <- "uskml.zip"
if (!file.exists(fil)) download.file(url, fil)
unzip(fil, exdir="uskml")
# read KML file
us <- rgdal::readOGR("./uskml/cb_2014_us_nation_20m.kml", "cb_2014_us_nation_20m")
sp::proj4string(quakes) <- sp::proj4string(us)
length(quakes)
# 1514
usquakes = quakes[us,]
length(usquakes)
# 1260
### visualize
plot(us)
# plot all quakes
points(quakes$longitude, quakes$latitude)
# plot just US
points(usquakes$longitude, usquakes$latitude)
结果图片:
谢谢@hrbrmstr!
答案 0 :(得分:4)
这样做的方式是:
library(sp)
library(maptools)
library(rgeos) # not entirely necessary
library(rgdal) # not entirely necessary
url <- "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.csv"
fil <- "all_week.csv"
if (!file.exists(fil)) download.file(url, fil)
quakes <- read.csv("all_week.csv", stringsAsFactors=FALSE)
coordinates(quakes) <- ~longitude+latitude
url <- "http://www2.census.gov/geo/tiger/GENZ2014/shp/cb_2014_us_nation_20m.zip"
fil <- "us.zip"
if (!file.exists(fil)) download.file(url, fil)
unzip(fil, exdir="us")
us <- readShapePoly("us/cb_2014_us_nation_20m.shp")
# alternatively
# us <- rgdal::readOGR("us/cbcb_2014_us_nation_20m.shp", "cb_2014_us_nation_20m")
# TRUE if in
in_us_rgeos <- rgeos::gIntersects(quakes, us, byid=TRUE)
# <NA> if in
in_us_over <- quakes %over% us
gIntersects
需要更长时间。 rgdal
和rgeos
可以成为在某些系统上工作的熊。 YMMV
使用美国KML需要(大部分)rgdal
:
# you wanted KML shapefile tho
url <- "http://www2.census.gov/geo/tiger/GENZ2014/kml/cb_2014_us_nation_20m.zip"
fil <- "uskml.zip"
if (!file.exists(fil)) download.file(url, fil)
unzip(fil, exdir="uskml")
us <- rgdal::readOGR("uskml/cb_2014_us_nation_20m.kml", "cb_2014_us_nation_20m")
proj4string(quakes) <- proj4string(us)
rgeos::gIntersects(quakes, us, byid=TRUE)
head(quakes %over% us)