将文件保存到R中的循环中的特定子文件夹中

时间:2017-02-21 12:35:35

标签: r loops directory subdirectory

我觉得我非常接近解决方案,但目前我无法弄清楚如何到达那里。

我遇到了以下问题。 在我的文件夹“Test”中,我有堆叠的数据文件,其名称为M1_1; M1_2M1_3,依此类推:/Test/M1_1.dat。 不,我想分开文件,以便获得:M1_1[1].dat, M1_1[2].dat, M1_1[3].dat等等。这些文件我想保存在特定的子文件夹中:Test/M1/M1_1[1]; Test/M1/M1_1[2]等等,以及Test/M2/M1_2[1], Test/M2/M1_2[2]等等。

现在我已经创建了子文件夹。我得到以下命令来分割文件,以便得到M1_1.dat[1]等等:

for (e in dir(path = "Test/", pattern = ".dat", full.names=TRUE, recursive=TRUE)){
  data <- read.table(e, header=TRUE)
  df <- data[ -c(2) ]
  out <- split(df , f = df$.imp)
    lapply(names(out),function(z){
    write.table(out[[z]], paste0(e, "[",z,"].dat"),
                sep="\t", row.names=FALSE, col.names = FALSE)})
}

现在,paste0命令可以获取我想要的拆分数据(虽然它是M1_1.dat[1]而不是M1_1[1].dat),但我无法弄清楚如何将这些数据存入我的子文件夹。

也许你有个主意?

提前致谢。

1 个答案:

答案 0 :(得分:1)

我不知道您的数据是什么样的,所以我将尝试使用baby names

上提供的性别数据集重新创建方案

假设zip文件夹中的所有文件都存储到&#34; inst / data&#34;

将所有文件路径存储到all_fi变量

all_fi <- list.files("inst/data", 
                         full.names = TRUE, 
                         recursive = TRUE, 
                         pattern = "\\.txt$")

    > head(all_fi, 3)
    [1] "inst/data/yob1880.txt" "inst/data/yob1881.txt"

将应用于目录

中每个文件的预设功能
f.it <- function(f_in = NULL){
# Create the new folder based on the existing basename of the input file
   new_folder <- file_path_sans_ext(f_in)
   dir.create(new_folder)

    data.table::fread(f_in) %>% 
    select(name = 1, gender = 2, freq = 3) %>% 
    mutate(
     gender = ifelse(grepl("F", gender), "female","male")
    ) %>% (function(x){

     # Dataset contains names for males and females
     # so that's what I'm using to mimic your split
     out <- split(x, x$gender)
      o <- rbind.pages(
             lapply(names(out), function(i){
             # New filename for each iteration of the split dataframes

             ###### THIS IS WHERE YOU NEED TO TWEAK FOR YOUR NEEDS
             new_dest_file <- sprintf("%s/%s.txt", new_folder, i)
             # Write the sub-data-frame to the new file
             data.table::fwrite(out[[i]], new_dest_file)
             # For our purposes return a dataframe with file info on the new
             # files...

              data.frame(
                file_name = new_dest_file,
                file_size = file.size(new_dest_file), 
                stringsAsFactors = FALSE)
            })
           )
        o
    })
}

现在我们可以循环:

注意:出于我的目的,我不会花时间遍历每个文件,出于您的目的,这将适用于您的每个初始文件,或者在我的情况下all_fi而不是{{1 }}

all_fi[2:5]