如何将R语言中列表results3转换为200行117列的DataFrame?
问题:将GitHub API返回的列表转换为指定结构的DataFrame
原R代码流程:
library(jsonlite) library(httpuv) library(httr) i<-1 results3 <- list(); for (a in 1:2) { getURL = paste0("https://api.github.com/search/commits?q=sentimentcommitter-date:2000-01-01..2023-01-20&sort=committer-date&order=asc&per_page=100&page=",a) req <- GET(getURL) data <- content(req) results3[[i]] <- data$items i <- i + 1 print(i) }
需求:将上述代码生成的列表results3转换为200行117列的DataFrame,使其结构与执行df <- jsonlite::fromJSON(results_json, simplifyDataFrame = TRUE, flatten = TRUE)后的结果一致。
解决方案
步骤1:合并列表中的所有提交项
results3是包含2个子列表的结构,每个子列表对应一页的100条提交记录。首先将两层列表合并为包含200个独立提交项的单层列表:
combined_items <- unlist(results3, recursive = FALSE)
步骤2:转换为扁平化DataFrame
使用jsonlite包的simplifyDataFrame函数,设置flatten=TRUE参数,直接将列表转换为符合要求的扁平化DataFrame:
df <- jsonlite::simplifyDataFrame(combined_items, flatten = TRUE)
或者结合dplyr包的bind_rows和flatten函数实现相同效果:
library(dplyr) df <- bind_rows(lapply(combined_items, function(item) jsonlite::flatten(as.data.frame(item))))
执行后得到的df就是200行117列的结构,和fromJSON指定参数后的输出完全一致——嵌套的JSON结构会被自动展开为顶层列,满足需求。
内容的提问来源于stack exchange,提问作者Erik Brole
相关产品推荐
相关产品推荐

