【问题标题】:Load multiple JSON files and iterate a function over the loaded objects加载多个 JSON 文件并在加载的对象上迭代一个函数
【发布时间】:2021-08-13 13:59:19
【问题描述】:

我正在寻找一种更优雅的方式来加载多个 JSON 文件并对每个文件应用一个函数,然后再组合所有生成的数据帧,以便我可以对主数据帧进行一些分析。

这是我目前拥有的一个示例:

## Load the files
page.1 <- fromJSON(file = "C:\\page-1.json")
page.2 <- fromJSON(file = "C:\\page-2.json")
page.3 <- fromJSON(file = "C:\\page-3.json")

## Call function (args: list name, page number)
results.1 <- myFunction(page.1, 1)
results.2 <- myFunction(page.2, 2)
results.3 <- myFunction(page.3, 3)

## Combine all results
all.results <- rbind(results.1, results.2, results.3)

我认为必须有一种方法可以使用 for() 循环,但我正在努力寻找一种方法来让 R 创建对象和文件名。像这样的伪代码:

## Create object to store results
all.results <- NULL

## Loop through files
for(i in 1:3){

  ## Load the file corresponding to i
  page.i <- fromJSON(file = paste("C:\\page-", i, ".json", sep = "")

  ## Apply the function to the file corresponding to i
  results.i <- myFunction(page.i, i)

  ## Add the output from the function to a 'master' data frame with the results from page 1 to 3
  all.results <- rbind(all.results, results.i)
} 

我也尝试让 lappy() 方法而不是 for() 循环工作,但我也遇到了空白。你能给我的任何帮助或指点都会很棒。

非常感谢,

J

【问题讨论】:

标签: r


【解决方案1】:

您可以将lapply 用作-

filenames <- list.files('path/', pattern = '\\.json$', full.names = TRUE)

result <- do.call(rbind, lapply(filenames, function(x) {
  page_num <- as.numeric(sub('.*page-(\\d+).*', '\\1', x))
  myFunction(fromJSON(x), page_num)
}))

【讨论】:

  • 谢谢 Ronak,这似乎是我所需要的,但是如何将页码作为 myFunction 中的第二个参数传递呢?页码位于文件名末尾的“.json”之前。例如。 "C:\\page-1.JSON"
猜你喜欢
  • 2018-12-22
  • 1970-01-01
  • 2020-03-27
  • 2018-08-19
  • 2012-09-09
  • 1970-01-01
  • 2018-05-12
相关资源
最近更新 更多