简体   繁体   中英

Get separate dataframes according to differents json files

I have three.json files,

bc1004.json
{"fl":1137379,"flnc":1134924,"flnc_polya":1134631}
bc1005.json
{"fl":1154374,"flnc":1151937,"flnc_polya":1151606}
bc1006.json
{"fl":765436,"flnc":760524,"flnc_polya":760304}

I would like to get 3 separate data.frames corresponding to the 3 files, with the filename corresponding to each data.frame. For the moment, I can get a list with the data.

filenames <- list.files("my_path/", pattern="*.json", full.names=TRUE)
myJSON <- lapply(filenames, function(x) rjson::fromJSON(file=x))
>myJSON

 [[1]]
[[1]]$fl
[1] 1137379

[[1]]$flnc
[1] 1134924

[[1]]$flnc_polya
[1] 1134631


[[2]]
[[2]]$fl
[1] 1154374

[[2]]$flnc
[1] 1151937

[[2]]$flnc_polya
[1] 1151606


[[3]]
[[3]]$fl
[1] 765436

[[3]]$flnc
[1] 760524

[[3]]$flnc_polya
[1] 760304

Try

myJSON_New <- lapply(myJSON, function(x) {cols <- names(x); x %>% 
  unique %>% 
  unlist %>% 
  as.data.frame %>% 
  tibble::rownames_to_column() %>% 
    mutate(rowname = rowname, 
     var1 = names(x))})

names(myJSON_New) <- filenames

with output

    > myJSON_New
$`./bc1004.json`
  rowname       .       var1
1       1 1137379         fl
2       2 1134924       flnc
3       3 1134631 flnc_polya

$`./bc1005.json`
  rowname       .       var1
1       1 1154374         fl
2       2 1151937       flnc
3       3 1151606 flnc_polya

$`./bc1006.json`
  rowname      .       var1
1       1 765436         fl
2       2 760524       flnc
3       3 760304 flnc_polya

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM