我有一些坐标需要获取其人口普查区(以及FIPS代码)。 我知道可以使用call_geolocator_latlon
来查询单个纬度/经度对(如此处所示),但这似乎对于我的目的不实用,因为该函数会向人口普查局的API发出单个调用,我估计将在我的大约200,000对上运行很长时间。
是否有更快的方法,例如使用block_groups
功能下载每个州的形状文件,并从那里将纬度/经度映射到人口普查区?
这段代码没有使用tigris
,而是利用sf::st_within()
函数来检查一个点数据框中的地块是否重叠。
我在这里使用tidycensus
来将加州的地块导入到R中。
library(sf)
ca <- tidycensus::get_acs(state = "CA", geography = "tract",
variables = "B19013_001", geometry = TRUE)
bbox <- st_bbox(ca)
my_points <- data.frame(
x = runif(100, bbox[1], bbox[3]),
y = runif(100, bbox[2], bbox[4])
) %>%
# convert the points to same CRS
st_as_sf(coords = c("x", "y"),
crs = st_crs(ca))
我在这里做了100点,以便能够使用ggplot()
来展示结果。但是对于1e6的重叠计算非常快,在我的笔记本电脑上只需要几秒钟。
my_points$tract <- as.numeric(st_within(my_points, ca)) # this is fast for 1e6 points
head(my_points) # tract is the row-index for overlapping census tract record in 'ca'
# but part would take forever with 1e6 points
library(ggplot2)
ggplot(ca) +
geom_sf() +
geom_sf(data = my_points, aes(color = is.na(tract)))
fips_codes
的数据框,因此您可以通过县名进行merge/join
操作。 - Nate上面的回答很棒。要获取人口普查区 ID,您也可以使用 st_join()
。在加利福尼亚州边界框内但不与州本身相交的点将被视为人口普查区 ID 中的 NA 值。
library(tigris)
library(tidyverse)
library(sf)
ca_tracts <- tracts("CA", class = "sf") %>%
select(GEOID, TRACTCE)
bbox <- st_bbox(ca_tracts)
my_points <- data.frame(
x = runif(200000, bbox[1], bbox[3]),
y = runif(200000, bbox[2], bbox[4])
) %>%
# convert the points to same CRS
st_as_sf(coords = c("x", "y"),
crs = st_crs(ca_tracts))
my_points_tract <- st_join(my_points, ca_tracts)
> my_points_tract
Simple feature collection with 200000 features and 2 fields
geometry type: POINT
dimension: XY
bbox: xmin: -124.4819 ymin: 32.52888 xmax: -114.1312 ymax: 42.0095
epsg (SRID): 4269
proj4string: +proj=longlat +datum=NAD83 +no_defs
First 10 features:
GEOID TRACTCE geometry
1 06025012400 012400 POINT (-114.6916 33.42711)
2 <NA> <NA> POINT (-118.4255 41.81896)
3 06053990000 990000 POINT (-121.8154 36.22736)
4 06045010200 010200 POINT (-123.6909 39.70572)
5 <NA> <NA> POINT (-116.9055 37.93532)
6 06019006405 006405 POINT (-119.511 37.09383)
7 06049000300 000300 POINT (-120.7215 41.3392)
8 <NA> <NA> POINT (-115.8916 39.32392)
9 06023990100 990100 POINT (-124.2737 40.14106)
10 06071008901 008901 POINT (-117.319 35.62759)
cenpy
和pysal
。 - akrun