2013-08-27 5 views
2

편집; 아래 답변.CSV 파일의 거리 주소를 R로 배치하는 방법은 무엇입니까?

배치 지오 코딩은 ggmap을 사용하여 이렇게 할 수 있습니다. 파일 이름은 내 것입니다. 코드는 내가 ggplot2과 모양 파일을 사용하여 뉴욕의 인구 조사 기관의지도를 만든 David Smith's Revolutions Blog Post

library(ggmap) 
#Read in csv file 
FDNYHouse = read.csv("Path to your csv file here.csv") 
#Get column header names if you don't already have them 
names(FDNYHouse) 
#Create a file of just addresses that need to be geocoded 
#You can require a state by replacing State below with New York if state was missing 
#Everything inside paste() is a column header from the csv file 
FDNYAddresses = with(FDNYHouse, paste(FacilityAddress, Borough, State, sep = ",")) 
#Now we can geocode the addresses 
FDNYLocations = geocode(FDNYAddresses) 
#The FDNYLocations file will have a lon and lat column representing your geocoded data 
#My next problem is getting the shape file projection to match my geocoded points 

에서 적응했다. 인구 조사 책자에 대한

FDNY Firehouse Locations

모양 파일을 찾을 수있다 : 다음, 나는 여기에서 다운로드 CSV 파일을 사용하여지도의 상단을 통해 누워 화재 주택의 거리 주소를 사용하여 데이터 프레임을 생성하고 싶습니다 여기에 (그것은 검은 2010 버전의) :

내 문제

NYC Shape File 데이터가 도시와 상태를 나열하지 않습니다있다, 그리고 나는이 주소를 잡을 수있는 함수를 작성하는 방법을 알고하지 않는 것이 Google로 지오 코드를 지정하십시오. ggmap과 같은 것을 사용합니다.

올바른 방향으로 조언이나 의견을 보내 주시면 감사하겠습니다. 나는 R에 익숙하지 않아서 stackoverflow가 쉬워진다.

편집 : A) 실제 데이터를 보거나 B) 내가 반복했다고 생각하는 질문이 3 세임을 알았습니까? 지난 3 년 동안 R에서 새로운 것은 없었던 것 같네요? 세상은 평평하고 사람들과 함께 움직여야합니다./rant

ggmap과 geocode() 함수를 사용하여 함수를 작성하지 않고 lat와 lon을 얻을 수 있습니다.

#As an example 
install.packages("ggmap") 
library(ggmap) 
geocode("San Francisco") 

문제는 다시, 그것이 내가 필요로하는 200 개 이상의 위도 및 경도 측정을 만들 수 있도록 저를 지오 코딩 할 필요없이, 도시 및 상태 데이터가 누락 내 csv 파일을 읽을 수 있도록 R을 말하는 방법입니다 한 번에 1 개의 주소.

두 번째 문제는이 데이터를 가져 와서 데이터 프레임을 만들고 이미 가지고있는 NYC 모양 파일에 추가하는 것입니다.

3 년 전의 답변은 경험이없는 사람에게 복잡하고 혼란 스럽습니다.이 게시물을 본 대부분의 사람들은 ... 또한 내 질문에 답하지 않는다고 생각합니다.

+0

소방서 위치 데이터는 주소와 자치구가 포함되어 있습니다. shapefile은 소방서 번호, 대대 및 부서를 제공합니다. 우편 번호에 데이터를 지정하는 방법을 묻는 질문을 보았지만 거리 주소를 다각형에 할당하는 방법을 묻는 질문은 없었습니다. 거리 주소 파일에 각 소방관의 우편 번호 및/또는 위도 - 경도 좌표를 수동으로 입력해야 할 수도 있습니다. 그러나 그것은 추측입니다. 거리 주소를 GIS 레이어에 지정하는 방법이있을 수 있습니다. 죄송합니다. 더 나은 조언을 드릴 수 없습니다. –

+0

다음 링크에서 RJ를 제공하여 Lat-Long 좌표가없는 GIS 레이어에 우편 주소를 할당 할 수있는이 웹 사이트를 발견했습니다. https://geoservices.tamu.edu/Services/Geocode/Default.aspx –

+0

게시 된 링크를 따라 가십시오. 'FDNY Firehouse Locations' 데이터를 사용하여 주소를 지오 코딩 할 수 있습니다. 도시 또는 주를 나열하지 않지만 더 정확한 지오 코딩을 위해 위치를 제한 할 수 있습니다. https://developers.google.com/maps/documentation/geocoding/index를 참조하십시오. 그런 다음 NYC shapefile에 대한 다각형 테스트에서 한 지점을 수행 할 수 있습니다. – JackeJR

답변

2

나는 최근에 비슷한 문제를 해결했습니다. 다음은 두 가지 코드입니다. 첫 번째 함수는 주소를 위도/경도로 변환합니다 (Google의 이용 약관을 준수하지 않는 경우 geo-coding의 경우 데이터 과학 툴킷을 좋은 독립 실행 형 대안으로 찾습니다). 두 번째 함수는 지정된 위도/경도 쌍을보고 어느 다각형 (센서스 관)에 그 좌표가 포함되어 있는지. choropleth지도를 작성하는 데 매우 유용합니다. 뉴욕 소방서 모양 파일을 보면

library("RJSONIO") #Load Library 
library("plyr") 
library("RODBC") 
library(maptools) 

getGeoCode <- function(gcStr) 
{ gcStr <- gsub(' ','%20',gcStr) #Encode URL Parameters 
    #Open Connection 
    connectStr <- paste('http://http://maps.googleapis.com/maps/api/geocode/json?address=',gcStr, sep="") 
    con <- url(connectStr) 
    data.json <- fromJSON(paste(readLines(con, warn = FALSE), collapse="")) 
    close(con) 
    #Flatten the received JSON 
    data.json <- unlist(data.json) 

    if (data.json["status"] == "OK" && data.json["results.geometry.location_type"] == "ROOFTOP") { 
    address <- data.json["results.formatted_address"] 
    lat <- data.json["results.geometry.location.lat"] 
    lon <- data.json["results.geometry.location.lng"] 
    gcodes <- data.frame("Address" = address, "Lon" = as.numeric(lon), "Lat" =  as.numeric(lat)) 
    return (gcodes) 
    } else return() 
} 

# Testing... 
geoCodes <- getGeoCode("Palo Alto,California") 
geoCodes 
# "-122.1430195" "37.4418834" 



# Required for TractLookup 
Washington <-readShapePoly("g:/USCensus/tl_2012_53_tract/tl_2012_53_tract")  
# US Census tract files (includes shape and data files) 


tractLookup <- function(x) { 
    # pt <- SpatialPoints(data.frame(x = -80.1, y = 26.3)) 
    pt <- SpatialPoints(data.frame(x = x$Lon, y = x$Lat)) 
    Mapping <- over(pt, Washington) # what index number does pt fall inside? 
    Mapping <- data.frame(
    "GEOID" = as.character(Mapping$GEOID), 
    "State" = as.character(Mapping$STATEFP) , 
    "County" = as.character(Mapping$COUNTYFP), 
    "Tract" = as.character(Mapping$TRACTCE), 
    "Tract_Name" = as.character(Mapping$NAME), 
    "INTPTLAT" = as.character(Mapping$INTPTLAT), 
    "INTPTLON" = as.character(Mapping$INTPTLON), 
    stringsAsFactors = FALSE) 
    Mapping[is.na(Mapping)] <- "NULL" 
return(Mapping) 
} 

tractLookup(data.frame("Lon" = -122, "Lat" = 47.5)) 
# GEOID State County Tract Tract_Name INTPTLAT  INTPTLON 
#2  321.02 +47.4851507 -121.9657839 

, 당신은 찾아 표준 미국 인구 모양 파일에서 지오이드 및 기관 정보 대신에 해당 필드를 반환하는 매핑 문을 변경 할 수 있어야한다 내 예.

0

이렇게 해보십시오.

# Geocoding a csv column of "addresses" in R 


#load ggmap 
library(ggmap) 


# Select the file from the file chooser 
fileToLoad <- file.choose(new = TRUE) 


# Read in the CSV data and store it in a variable 
origAddress <- read.csv(fileToLoad, stringsAsFactors = FALSE) 


# Initialize the data frame 
geocoded <- data.frame(stringsAsFactors = FALSE) 


# Loop through the addresses to get the latitude and longitude of each address and add it to the 
# origAddress data frame in new columns lat and lon 
for(i in 1:nrow(origAddress)) 

{ 
# Print("Working...") 
result <- geocode(origAddress$addresses[i], output = "latlona", source = "google") 
origAddress$lon[i] <- as.numeric(result[1]) 
origAddress$lat[i] <- as.numeric(result[2]) 
origAddress$geoAddress[i] <- as.character(result[3]) 
} 


# Write a CSV file containing origAddress to the working directory 
write.csv(origAddress, "geocoded.csv", row.names=FALSE) 

enter image description here