如何在 R 中对无效/不正确位置的表进行地理编码



我从推特上收集了不同用户位置的数据。我正在尝试在 R 的地图中绘制这些数据。问题是用户提供了无效/不正确的地址,导致地理编码功能失败。如何避免此故障?有没有办法检查此错误情况而不继续?例如,对于任何文件地理编码9.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({ # 不运行地理编码函数}

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

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

相关内容

最新更新