【发布时间】: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