【发布时间】:2018-11-29 14:22:10
【问题描述】:
这是我需要帮助的时候了,因为我已经尝试了所有方法来解决我的 FOR 循环的问题。 我想使用 API 从地址进行地理编码,我使用了一个非常清晰的函数,以及更多的数据框来安排每个步骤的结果并检查是否存在问题,但现在我找不到更多...
addresses:是我的带有address列的数据框,结果会放在那里
"address_ID","address","accuracy","lon_geop","lat_geop","address_geop","geopID","success"
1,"4 Kiricheneck 9990"
2,"10 Kiricheneck 9990"
3,"26 Kiricheneck 9990""
4,"27 Kiricheneck 9990"
5,"6 Avenue D'oberkorn 4640"
代码:
plcUrl <- "https://apiv3.geoportail.lu/geocode/search?queryString="
getGeoDetails <- function(address)
{
query <- paste(addresses$address)
strurl <- as.character(paste(plcUrl,query))
rd <- fromJSON(URLencode(strurl))
df <- data.frame(matrix(unlist(rd), nrow = 22, byrow = T),stringsAsFactors = FALSE)
colnames(df)[1] <- "results_geop"
answer <- data.frame(lat = NA, lon = NA, accuray = NA, address_geop = NA, success = NA, geopID = NA)
answer$status <- df$results_geop[22]
#return Na's if we didn't get a match
if (df$results_geop[22] != "TRUE")
{
return(answer)
}
#else, extract what we need from the GeoPortail server reply into a dataframe
answer$lat <- df$results_geop[9]
answer$lon <- df$results_geop[8]
answer$accuracy <- df$results_geop[21]
answer$geopID <- df$results_geop[19]
answer$address_geop <- df$results_geop[6]
answer$success <- df$results_geop[22]
return(answer)
}
#initialise a dataframe to hold the results
geocoded <- data.frame()
startindex <- 1
row_addresses <- as.numeric(rownames(addresses))
# Start the geocoding process - address by address
for (j in startindex:row_addresses)
{
#query the GeoPortail geocoder
result = getGeoDetails(addresses[j])
print(result$status)
result$index <- j
#append the answer to the results file
geocoded <- rbind(geocoded, result)
#now we add all the results to the main data
addresses$lat_geop[j] <- geocoded$lat[j]
addresses$lon_geop[j] <- geocoded$lon[j]
addresses$accuracy[j] <- geocoded$accuracy[j]
addresses$address_geop[j] <- geocoded$address_geop[j]
addresses$geopID[j] <- geocoded$geopID[j]
addresses$success[j] <- geocoded$success[j]
return(j)}
最后: 警告信息: 在 startindex:row_addresses : 数值表达式有 5 个元素:只使用第一个
地址数据框只有第一行效果好,其他为空。 我试过了:
- 索引:for(i in 1:x)
- 为结果和循环(索引 i)构建空数据框:d[i, ] = c(x, y, z)
- 中断命令
- 下一条命令
还没有任何帮助...我的其他 for 循环可以完成这项工作,所以非常令人沮丧。
【问题讨论】:
-
您的错误很可能在这里:
row_addresses <- as.numeric(rownames(addresses))返回一个包含 5 个元素的向量,然后您尝试在以下 for 循环索引中使用 row_addresses。在 for 循环中只需使用for (j in startindex:nrow(addresses)) -
我试过了,但没有任何改变:for (j in startindex:nrow(addresses)) for (j in 1:nrow(addresses)) for (j in 1:5)
标签: r loops for-loop geocoding