【问题标题】:GET more objects using httr package in R在 R 中使用 httr 包获取更多对象
【发布时间】:2016-03-12 04:11:00
【问题描述】:

我使用 httr 包从 Data API 获取数据:

request3 <- GET(url = "https://api.data-api.io/xxxxx/", add_headers('x-dataapi-key' = "xxxxx"), query = list(oib = "18527887472"))

如何在一行代码中获取更多对象?假设我有一个向量:

oibreq <- c("18527887472", "92680516748", "00045103869")

我想为这 3 个“查询”获取对象。很长的路要走 3 次调用 GET 函数:

 request1 <- GET(url = "https://api.data-api.io/xxxx", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "18527887472"))
request2 <- GET(url = "https://api.data-api.io/v1/eoglasna/", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "00045103869"))
request2 <- GET(url = "https://api.data-api.io/v1/eoglasna/", add_headers('x-dataapi-key' = "xxxx"), query = list(oib = "92680516748"))

有没有更快的方法来做到这一点?如果我有 100 个oibreqelements,那就有问题了。

【问题讨论】:

    标签: r get httr


    【解决方案1】:

    您可以编写自己的函数,然后通过 lapply() 将对象 ID 向量传递给函数:

    my_get <- function(object) {
      GET(url = "https://api.data-api.io/v1/eoglasna/", 
          add_headers('x-dataapi-key' = "xxxx"), 
          query = list(oib = object))
    }
    lapply(oibreq, my_get)
    

    【讨论】:

    • 我修改代码以包含附加功能:my_get &lt;- function(object) { fromJSON(toJSON(content(GET(url = "https://api.data-api.io/v1/eoglasna/", add_headers('x-dataapi-key' = "59dd75a6525e"), query = list(oib = object)), type = "application/json"), null = "null"), flatten = TRUE) } req1 &lt;- lapply(oibreq, my_get) 并生成列表列表...,例如。 G。 [[2]] [[2]][[1]] [[2]][[1]]$datum [1] "2015-10-19T09:03:30+02:00"
    • @Mislav 是的……那是有道理的。但是你为什么要使用fromJSON(toJSON(...))...那里不需要toJSON()
    • 因为如果我不使用toJSON():Error: Argument 'txt' must be a JSON string, URL or file. SO,我仍然没有得到想要的结果。我想获取 data.frame,但我得到了带有列表列表的相同奇怪对象...
    • @Mislav 看看? content,它会自动解析为 json,所以你可以跳过所有这些。
    【解决方案2】:

    我找到了我的问题的答案:

    req <- list()
    my_get <- for (i in 1:length(oibreq)) {
      reqOP <- rbind(fromJSON(toJSON(content(GET(url = "https://api.data-api.io/v1/eoglasna/", 
                                  add_headers('x-dataapi-key' = "xxx"), 
                                  query = list(oib = oibreq[i])), type = "application/json"), null = "null"), flatten = TRUE))
      req[[i]] <- reqOP
    }
    big_data <- do.call(rbind, req)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多