继续...使用 R 从 API 中提取数据

A continuation of... Extracting data from an API using R

我是这方面的超级新手,正在为我的论文研究 R。这个答案中的代码最终对我有用(),但我不知道如何向它添加循环。当我需要所有 3360 时,我不断获得 API 的第一页。 这是代码:

    library(httr)
    library(jsonlite)
    r1 <- GET("http://data.riksdagen.se/dokumentlista/? 
    sok=&doktyp=mot&rm=&from=2000-01-01&tom=2017-12- 31&ts=&bet=&tempbet=&nr=&org=&iid=&webbtv=&talare=&exakt=&planering=&sort=rel&sortorder=desc&rapport=&utformat=json&a=s#soktraff")

r2 <- rawToChar(r1$content)

class(r2)
r3 <- fromJSON(r2)

r4 <- r3$dokumentlista$dokument

当我到达r4时,它已经是一个数据帧了。

拜托,谢谢!

编辑:最初,我无法获得包含页面信息的 url。现在我有了它(下)。我仍然无法循环播放它。 “http://data.riksdagen.se/dokumentlista/?sok=&doktyp=mot&rm=&from=2000-01-01&tom=2017-12-31&ts=&bet=&tempbet=&nr=&org=&iid=&webbtv=&talare=&exakt=&planering=&sort=rel&sortorder=desc&rapport=&utformat=json&a=s&p=

我想你可以从r3中提取下一页的url,如下所示:

next_url <- r3$dokumentlista$`@nasta_sida`
# you need to re-check this, but sometimes I'm getting white spaces within the url, 
# you may not face this problem, but in any case this line of code solved the issue 
next_url <- gsub(' ', '', n_url)

GET(next_url)

更新

我用 10 页的页码尝试了 url,它起作用了

my_dfs <- lapply(1:10, function(i){
  my_url <- paste0("http://data.riksdagen.se/dokumentlista/?sok=&doktyp=mot&rm=&from=2000-01-01&tom=2017-12-31&ts=&bet=&tempbet=&nr=&org=&iid=&webbtv=&talare=&exakt=&planering=&sort=rel&sortorder=desc&rapport=&utformat=json&a=s&p=", i)
  r1 <- GET(my_url)
  r2 <- rawToChar(r1$content)
  r3 <- fromJSON(r2)
  r4 <- r3$dokumentlista$dokument
  return(r4)
})

更新 2:

提取的数据帧很复杂(例如,某些列是数据帧列表),这就是为什么简单的 rbind 在这里不起作用,您必须在堆叠之前进行一些预处理数据在一起,像这样的东西会起作用

my_dfs %>% lapply(function(df_0){
      # Do some stuff here with the data, and choose the variables you need
      # I chose the first 10 columns to check that I got 200 different observations
      df_0[1:10]
    }) %>% do.call(rbind, .)