我正在try 使用经度和纬度创建一个点文件,然后使用st_Join和st_in将它们与人口普查区域进行匹配.但这些积分最终都落在了堪萨斯州.如果您使用的是带有API的tidycopcount库,则有可重复使用的代码:
虚拟数据点的代码主要在科罗拉多州,区域边界在科罗拉多州和堪萨斯州:
library(tidycensus)
library(sf)
library(dplyr)
library(tidyverse)
# Set seed for reproducibility
set.seed(42)
# Generate dummy data for points in New York
points <- data.frame(
longitude = runif(300, min = -109, max = -102), # Approximate longitude boundaries of Colorado
latitude = runif(300, min = 36.993076, max = 41) # Approximate latitude boundaries of Colorado
)
# Print the first few rows of the dummy data
points <- st_as_sf(points, coords = c("longitude", "latitude"), crs = "ESRI:102003")
tract2010 <- get_decennial(geography = "tract", variables = "P001001", year = 2010,
state = as.list(c("Colorado", "Kansas")), geometry = TRUE)
tract2010$state_code <- substr(tract2010$GEOID, 1, 2)
table(tract2010$state_code)
# make same CRS
tract2010 <- st_transform(tract2010, st_crs(points))`
将其绘制在传单中,以确保这些点位于正确的位置:
# test where it is
library(leaflet)
leaflet() %>%
addTiles() %>%
addMarkers(data = points)
运行连接并判断匹配.从表格中,所有的分数都在州代码20(堪萨斯州)
#spatial join
points <- st_join(points, tract2010, join = st_within)
table(points$state_code, useNA = "always")