【发布时间】: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
【问题讨论】:
-
这能回答你的问题吗? Read many files in parallel and extract data
标签: r