从坐标中获取人口普查区域代码

9

我有一个包含经纬度坐标的数据集,想要获取相应的人口普查区域(census tract)。是否有数据集或API可以实现这一功能?

我的数据集看起来像这样:

       lat       lon   
1 40.61847 -74.02123   
2 40.71348 -73.96551   
3 40.69948 -73.96104    
4 40.70377 -73.93116   
5 40.67859 -73.99049   
6 40.71234 -73.92416   

我想要添加一个带有相应人口普查区的列。
最终输出应该长这个样子(这些不是正确的数字,只是一个例子)。
       lat       lon     Census_Tract_Label   
1 40.61847 -74.02123                   5.01
2 40.71348 -73.96551                     20
3 40.69948 -73.96104                     41
4 40.70377 -73.93116                  52.02
5 40.67859 -73.99049                     58
6 40.71234 -73.92416                     60
1个回答

13

tigris 包含一个名为 call_geolocator_latlon 的函数,应该可以满足你的需求。以下是使用该函数的代码:

    > coord <- data.frame(lat = c(40.61847, 40.71348, 40.69948, 40.70377, 40.67859, 40.71234),
    +                     long = c(-74.02123, -73.96551, -73.96104, -73.93116, -73.99049, -73.92416))
    > 
    > coord$census_code <- apply(coord, 1, function(row) call_geolocator_latlon(row['lat'], row['long']))
    > coord
           lat      long     census_code
    1 40.61847 -74.02123 360470152003001
    2 40.71348 -73.96551 360470551001009
    3 40.69948 -73.96104 360470537002011
    4 40.70377 -73.93116 360470425003000
    5 40.67859 -73.99049 360470077001000
    6 40.71234 -73.92416 360470449004075

据我理解,这15位代码是若干个代码组合而成的(前两位代表州,接下来的三位代表县,接下来的六位代表地块)。如果只想获取人口普查地块代码,只需使用substr函数提取这六位数字即可。

    > coord$census_tract <- substr(coord$census_code, 6, 1)
    > coord
           lat      long     census_code census_tract
    1 40.61847 -74.02123 360470152003001       015200
    2 40.71348 -73.96551 360470551001009       055100
    3 40.69948 -73.96104 360470537002011       053700
    4 40.70377 -73.93116 360470425003000       042500
    5 40.67859 -73.99049 360470077001000       007700
    6 40.71234 -73.92416 360470449004075       044900

希望这能有所帮助!


有没有办法将 call_geolocator_latlon 向量化?我想对相对较大数量(200,000)的坐标执行此操作。 - mlinegar
1
这个特定的函数看起来只能一次执行单个API调用。人口普查局的API文档提到了通过发送特殊格式的csv进行批量地理编码。他们给出的示例curl命令是:curl --form addressFile=@localfile.csv --form benchmark=9 https://geocoding.geo.census.gov/geocoder/locations/addressbatch --output geocoderesult.csv - Danny Farnand
1
这非常有帮助!如果我想指定特定的年份,我需要做什么修改?我尝试了 coord$census_code <- apply(coord, 1, function(row) call_geolocator_latlon(row['lat'], row['long'], vintage = 2010))coord$census_code <- apply(coord, 1, function(row) call_geolocator_latlon(row['lat'], row['long'], rep(na, nrow(coord)), rep(2010, nrow(coord))),还添加了 benchmarkvintage 列,然后执行 coord$census_code <- apply(coord, 1, function(row) call_geolocator_latlon(row['lat'], row['long'], row['benchmark'], row['vintage']) - cskn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接