【问题标题】:Munging a recursive discogs list修改一个递归的 discogs 列表
【发布时间】:2019-12-17 11:07:53
【问题描述】:

使用 discogs,我获得了一个给定爵士音乐家的发行列表,如下所示:

releases <- list()
artists <- list()
artistURL <- "https://api.discogs.com/artists/"
library(jsonlite)
a <- function(artistcode){
  for(i in 0:3){
    artistset <- fromJSON(paste0(artistURL, artistcode, "/releases?page=", i))
    message("Retrieving page ", i)

    releases[[i+1]] <- (as.data.frame(artistset$releases.main_release))
      }
  return(artistset)
  message("Total rows=", dim(artistset[[2]])[1] )
}

temp<-a('265634') # art tatum 265634
temp$releases$title # shows first 50 albums...where's the rest?

经过检查,您会看到temp 是两个列表,第二个称为releases。发行中包含 50 张专辑。但是,我在 fromJSON 命令中要求提供三页输出,但在 temp 中有 22 页结果:

str(temp$pagination)  # there are 22 pages of 50 lines per page

如何将这位艺术家的所有标题和其他数据(价值 22 页)提取到数据框中?一直在搞乱purrr 无济于事。感谢您的帮助!

【问题讨论】:

    标签: r nested-lists purrr discogs-api


    【解决方案1】:

    这应该会更好。 releases 仅在您的函数范围内定义,并未返回到全局环境。还更改了函数以使用 JSON 中的 pages 变量来构造循环:

    a <- function(artistcode){
      releases <- list()
      metadata <- fromJSON(paste0(artistURL, artistcode, "/releases?page=", 1))
      for (i in 1:metadata$`pagination`$pages){
        message("Retrieving page ", i)
        Sys.sleep(2) #added as I was being rate limited
        releases[[i]] <- fromJSON(paste0(artistURL, artistcode, "/releases?page=", i))$releases
      }
      return(releases)
    }
    
    temp<-a('265634') # art tatum 265634
    
    temp[[1]] # page 1
    temp[[2]] # page 2
    

    【讨论】:

    • 嘿,这太好了@Chris,非常感谢!我看到你是如何利用分页列表中的 pages 字段来构建函数的。
    猜你喜欢
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 2015-12-07
    • 1970-01-01
    相关资源
    最近更新 更多