【发布时间】:2019-11-09 00:03:23
【问题描述】:
我正在使用https://ipstack.com 的帮助来对 IP 地址进行地理编码,但我很难在短时间内对所有 1200 个地址进行地理编码。
使用 R,我已将 URL 收集到一个列表中(例如 http://api.ipstack.com/[IP address]?access_key=[access key]),并且可以使用 read_json 读取每个 URL 的 json 数据。但是我无法开发一个循环来从每个 URL 中提取数据。
library(RCurl)
library(jsonlite)
x <- c("http://api.ipstack.com/178.140.119.217?access_key=[access_key]", "http://api.ipstack.com/68.37.21.125?access_key=[access_key]", "http://api.ipstack.com/68.10.255.89?access_key=[access_key]")
read_json(x)
Error in file(path) : invalid 'description' argument
我正在寻找一种能够读取多个 IP 地址并将信息附加到数据帧的解决方案。
*编辑 1:仍然卡住,但我在循环方面取得了一些进展,
library(RCurl)
library(jsonlite)
url_lst = as.character(df$URL)
output = NULL
for (i in url_lst) {
x = as.data.frame(read_json(i))
output = rbind(output,x)
}
但是,这会导致错误:
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, : arguments imply differing number of rows: 1, 0
同样,代码只产生 8 个观察值,而不是 1200 个。
*编辑 2:Bill Ash 的回答比我更深入,但看起来 JSON 数据中的某些值不允许代码成功。
Bill Ash 的代码:
library(httr)
library(tibble)
library(purrr)
library(jsonlite)
ip_addresses <- core_members$ip_address
# a simple function
ip_locate <- function(your_vector_of_ip_addresses, access_key) {
ip <- your_vector_of_ip_addresses
map_df(ip, ~{
out <- httr::GET(url = paste0("http://api.ipstack.com/", .,
"?access_key=", access_key))
resp <- fromJSON(httr::content(out, "text"), flatten = TRUE)
tibble::tibble(ip = resp$ip,
country = resp$country_name,
region = resp$region_name,
city = resp$city,
zip = resp$zip,
lat = resp$latitude,
lng = resp$longitude)
})
}
ip_info <- ip_locate(your_vector_of_ip_addresses = ip_addresses,
access_key = "[access_key]")
# output
ip_info %>%
head()
错误开始的地方
ip_info <- ip_locate(your_vector_of_ip_addresses = ip_addresses,
access_key = "[access_key]")
Error: All columns in a tibble must be 1d or 2d objects:
* Column `zip` is NULL
9.
stop(cnd)
8.
abort(error_column_must_be_vector(names_x[is_xd], classes))
7.
check_valid_cols(x)
6.
lst_to_tibble(xlq$output, .rows, .name_repair, lengths = xlq$lengths)
5.
tibble::tibble(ip = resp$ip, country = resp$country_name, region = resp$region_name,
city = resp$city, zip = resp$zip, lat = resp$latitude, lng = resp$longitude)
4.
.f(.x[[i]], ...)
3.
map(.x, .f, ...)
2.
map_df(ip, ~{
out <- httr::GET(url = paste0("http://api.ipstack.com/",
., "?access_key=", access_key))
resp <- fromJSON(httr::content(out, "text"), flatten = TRUE) ...
1.
ip_locate(your_vector_of_ip_addresses = ip_addresses, access_key = "[access_key]")
因为我只需要这些 IP 地址的坐标,我相信这已经解决了。希望有人愿意继续就这个问题提出建议,但我不会再更新了。
【问题讨论】:
-
?read_json表示path= 是“磁盘上的文件”。你试过stream_in(url(..))吗? -
@r2evans 我确实尝试过,它说“参数'con'必须是一个连接”。我不完全确定如何补救。