【问题标题】:How to geocode a table of invalid/incorrect locations in R?如何对 R 中的无效/不正确位置表进行地理编码?
【发布时间】:2018-01-15 01:49:14
【问题描述】:

我从 twitter 收集了不同用户位置的数据。我正在尝试在 R 中的地图中绘制这些数据。问题是用户提供了无效/不正确的地址,导致地理编码功能失败。我怎样才能避免这种失败?有没有办法检查这个错误情况而不继续?例如,对于任何文件 geocode9.csv,用户位置数据都是这样的。

可用位置, 水牛, 纽约, thsjf, 美国华盛顿 密歇根州, nkjnt, 篮球, ejhrbvw

library(ggmap)
fileToLoad <- file.choose(new = TRUE)
origAddress <- read.csv(fileToLoad, stringsAsFactors = FALSE)
geocoded <- data.frame(stringsAsFactors = FALSE)
for(i in 1:nrow(origAddress))
{

  result <- geocode(origAddress$available_locations[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.csv(origAddress, "geocoded.csv", row.names=FALSE)

当代码通过位置列表的“thsjf”运行时,会引发错误。我怎样才能克服这个错误?我想要类似的东西, if(false){ # 不运行地理编码功能}

【问题讨论】:

  • 你能以某种方式捕捉到这个错误吗?地理编码的正常工作流程是只允许用户提交从地理编码服务本身中选择的地址。因此,您遇到的问题永远不会真正发生。
  • @TimBiegeleisen 这就是我想要做的。我无法捕捉到这个错误。我努力了。 if(geocode(origAddress$available_locations[i], output = "latlona", source = "google")){ //找到坐标} .它也以这种方式给出错误,说 if 中的条件不是逻辑值。
  • 那么你尝试过使用try catch吗? Google 的地理编码服务只会为错误的地址返回一个空的 JSON 响应(我认为)。
  • 是的,我使用了 tryCatch。但这并没有解决问题。我想我找到了解决这个问题的方法。诀窍是不要写这一行:origAddress$geoAddress[i]

标签: r google-maps-api-3 jupyter geocode twitter-rest-api


【解决方案1】:

如果这些地址实际上是错误的,我不确定如何对这些地址进行地理编码。如果它是错误的,机器怎么会发现它?我认为您需要更正地址,然后对所有内容进行地理编码。这是一些示例代码。

#load ggmap
library(ggmap)

startTime <- Sys.time()

# 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)

endTime <- Sys.time()
processingTime <- endTime - startTime
processingTime

查看此处了解更多信息。

http://www.storybench.org/geocode-csv-addresses-r/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多