我刚刚遇到了这个功能强大的R包,但不幸的是,它还不能找到如何并行解析响应为JSON格式的urls列表。
举个简单的例子,假设我有一个城市列表(在瑞士):
list_cities <- c("Winterthur", "Bern", "Basel", "Lausanne", "Lugano")下一步,我想为列出的每个城市找到通往苏黎世的公共交通连接。我可以使用以下传输api来查询公共时间表数据:
https://transport.opendata.ch使用httr包,我可以为每个城市发出如下请求:
for (city in list_cities) {
r <- GET(paste0("http://transport.opendata.ch/v1/connections?from=", city, "&to=Zurich&limit=1&fields[]=connections/duration"))
cont <- content(r, as = "parsed", type = "application/json", encoding = "UTF-8")
}以获取单个旅程的持续时间。然而,我有一个更长的列表和更多的目的地。这就是为什么我在寻找一种并行发出多个请求的方法。
发布于 2018-02-25 22:16:56
注意,我没有对此进行测试,但首先,您需要初始化您的并行工作线程
library(parallel)
cl <- makeCluster(detectCores() - 1)
clusterEvalQ(cl, { library(Rcrawler) }) # load required packages onto each parallel worker使用相关命令执行Make函数
custom_parse_json <- function(city) {
r <- GET(paste0("http://transport.opendata.ch/v1/connections?from=", city, "&to=Zurich&limit=1&fields[]=connections/duration"))
cont <- content(r, as = "parsed", type = "application/json", encoding = "UTF-8")
return(cont)
}将函数导出到每个并行工作
clusterExport(cl, c("custom_parse_json"))遍历城市列表
parLapply(cl, list_cities, function(i) custom_parse_json(i))这将返回您的JSON内容的列表。
https://stackoverflow.com/questions/48973141
复制相似问题