【发布时间】:2017-11-28 23:21:41
【问题描述】:
我在将县分配给某些城市时遇到了问题。通过acs包查询时
> geo.lookup(state = "NY", place = "New York")
state state.name county.name place place.name
1 36 New York <NA> NA <NA>
2 36 New York Bronx County, Kings County, New York County, Queens County, Richmond County 51000 New York city
3 36 New York Oneida County 51011 New York Mills village
,例如,您可以看到“纽约”有一堆县。洛杉矶、波特兰、俄克拉荷马州、哥伦布等地也是如此。如何将这些数据分配给“县”?
以下代码当前用于将“county.name”与相应的县 FIPS 代码匹配。不幸的是,它仅适用于查询中仅输出一个县名的情况。
脚本
dat <- c("New York, NY","Boston, MA","Los Angeles, CA","Dallas, TX","Palo Alto, CA")
dat <- strsplit(dat, ",")
dat
library(tigris)
library(acs)
data(fips_codes) # FIPS codes with state, code, county information
GeoLookup <- lapply(dat,function(x) {
geo.lookup(state = trimws(x[2]), place = trimws(x[1]))[2,]
})
df <- bind_rows(GeoLookup)
#Rename cols to match
colnames(fips_codes) = c("state.abb", "statefips", "state.name", "countyfips", "county.name")
# Here is a problem, because it works with one item in "county.name" but not more than one (see output below).
df <- df %>% left_join(fips_codes, by = c("state.name", "county.name"))
df
返回:
state state.name county.name place place.name state.abb statefips countyfips
1 36 New York Bronx County, Kings County, New York County, Queens County, Richmond County 51000 New York city <NA> <NA> <NA>
2 25 Massachusetts Suffolk County 7000 Boston city MA 25 025
3 6 California Los Angeles County 20802 East Los Angeles CDP CA 06 037
4 48 Texas Collin County, Dallas County, Denton County, Kaufman County, Rockwall County 19000 Dallas city <NA> <NA> <NA>
5 6 California San Mateo County 20956 East Palo Alto city CA 06 081
为了保留数据,left_join 最好匹配为“查找包含 place.name 的 county.name(名称中不附加 xy city ),或者默认选择第一项。很高兴看到如何做到这一点。
总的来说:我认为,没有比这种方法更好的方法了吗?
感谢您的帮助!
【问题讨论】:
标签: r dplyr match geocoding acs