将深度嵌套的文件保存到具有特定文件名的特定目录中 [英] Saving deeply nested files to specific directories with specific filenames

查看:80
本文介绍了将深度嵌套的文件保存到具有特定文件名的特定目录中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个三级嵌套列表:

Given a 3 level nested list:

mylist <- list("1000"=list("cars"=list("fast"=mtcars[1:10,], "slow"=mtcars[11:15,]), "flower"=iris), "2000"=list("tooth"=ToothGrowth, "air"=airquality, "cars"=list("cruiser"=mtcars[5:12,], "fast"=mtcars[1:3,], "mild"=mtcars[9:18,]))) 

(即:mylist$1000$cars$fast,其中fast是数据帧,而cars1000mylist中的嵌套列表)

(ie: mylist$1000$cars$fast, where fast is a dataframe, and cars and 1000 are nested lists in mylist)

我想将每个最里面的数据帧(即:fast)另存为.csv,并以df名称作为文件名,例如:fast.csv文件保存在以第二级列表命名的目录中,即:~/1000/fast.csv.

I'd like to save each innermost dataframe, (ie: fast) as a .csv with the df name as it's file name, ie: fast.csv, and I want the file to be saved in a directory that is named after the second level of list, ie: ~/1000/fast.csv.

每个目录已经存在,因此不需要创建新的10002000目录.

Each directory already exists, so I do not need to create a new 1000 and 2000 directory.

我的直觉是做一个嵌套的lapplylapply/mapply组合...但是要跟踪不同的级别及其名称对我构成了挑战.我知道purrr具有iwalk功能,但是我不确定如何在深度嵌套的列表中使用它.

My instinct is to do a nested lapply or lapply/mapply combination...but keeping track of the different levels and their names is challenging me. I know that purrr has the iwalk function, but I'm not sure how to use it within deeply nested list.

我当前的尝试失败.

lapply(mylist, function(d){
  lapply(names(mylist), function(id){
    lapply(names(d$cars), function(s){
    lapply(d$cars, function(a){
        write.csv(a, paste0(outdir, id, "/", s, ".csv"))})})})})

输出结果将单个文件以多种名称保存到所有目录中.即:~/1000/cruiser.csv~/1000/fast.csv~/1000/mild.csv~/2000/cruiser.csv~/2000/fast.csv~/2000/mild.csv ...,其中所有文件实际上只是mylist$2000$cars$mild

The output results in a single file being saved under multiple names into all the directories. ie: ~/1000/cruiser.csv, ~/1000/fast.csv, ~/1000/mild.csv, ~/2000/cruiser.csv, ~/2000/fast.csv, ~/2000/mild.csv ... where all the files are actually just a csv of mylist$2000$cars$mild

推荐答案

假定子文件夹在工作目录中:

Assuming the sub-folders are within the working directory:

purrr::iwalk(mylist, function(el, folder){
  purrr::walk(el,
              function(sub_el, folder){
                if(class(sub_el) == "list"){
                  purrr::iwalk(sub_el,
                               function(dat, dat_name, folder){
                                 write.csv(dat,
                                           # below line specifies file path of new file
                                           paste0(folder, "/", dat_name, ".csv"))
                               },
                               folder = folder)
                }
              },
              folder = folder)
})

这篇关于将深度嵌套的文件保存到具有特定文件名的特定目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆