【问题标题】:Add filename column to dataframe from multiple json imports从多个 json 导入中将文件名列添加到数据框
【发布时间】:2020-10-06 01:36:26
【问题描述】:

我有多个包含日期的 .json 文件。我想在 R 中导入所有 .json 文件以创建一个数据框并添加包含文件名的列。

2020-06-15.json:

[{"title":"Moral Machine","title_link":"http://moralmachine.mit.edu/"}]

2020-06-16.json:

[{"title":"De Monitor","title_link":"http://demonitor.ncrv.nl/"}]

然后我创建一个数据框

test_path <- "data"
test_files <- list.files(test_path, pattern = "*.json")

test_files %>%
  map_df(~fromJSON(file.path(test_path, .), flatten = TRUE))

期望的输出:

          title                   title_link       file_name
1 Moral Machine http://moralmachine.mit.edu/ 2020-06-15.json
2    De Monitor    http://demonitor.ncrv.nl/ 2020-06-16.json

【问题讨论】:

  • 任何 json 文件是否只包含一个观察结果?

标签: r json


【解决方案1】:

使用来自data.tablerbindlist

library(data.table)

file_names <- list.files(path = test_path, pattern = '.*json')

data_list <- lapply(file_names, function(z){
  dat <- myFunction(z) #your function to read and clean json files
  dat$file_name <- z
  return(dat)
})

combined_data <- rbindlist(l = data_list, use.names = T, fill = T)

由于我不知道您的 JSON 文件的结构,我假设您有一个名为 myFunction 的函数来读取和清理数据。

【讨论】:

  • 我添加了我的两个示例 .json 文件的内容,对吧?
【解决方案2】:
library(jsonlite)

test_files_full <- list.files(test_path, pattern = "*.json",full.names=TRUE) # to get the full path string

test_files <- list.files(test_path, pattern = "*.json")

t(sapply(seq_along(test_files), function(x) 
            c(fromJSON(test_files_full[x]),file_name=test_files[x])))

给予,

     title           title_link                     file_name        
[1,] "Moral Machine" "http://moralmachine.mit.edu/" "2020-06-15.json"
[2,] "De Monitor"    "http://demonitor.ncrv.nl/"    "2020-06-16.json"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多