通过R将文件移到相同名称的文件夹中

时间:2019-01-01 11:46:54

标签: r

  

我有一个文件夹,其中包含不同的示例csv文件和相同名称的文件夹:

files name:-
sample_190612.csv
sample_729924.csv  
sample_729794.csv 
sample_780414.csv
sample_780388.csv 
................
............
folders:-
sample_190612
sample_729924
sample_729794 
sample_780414
sample_780388
............
............... 
  

如何将这些文件移入文件的名称文件夹

     

预期的输出:文件夹包含文件:-

  Folder:-     sample_190612 
  File:        sample_190612.csv


  Folder:-     sample_729924  
  file:        sample_729924 .csv


  Folder:-    sample_780414 
  file:       sample_780414.csv

1 个答案:

答案 0 :(得分:0)

我不确定您要做什么。 但是下面的代码可以用逗号分隔字符串“ AC ###”(如Parfait要求的那样), 并使用第一列创建文件夹, 并使用“ AC ###”字符串保存文件。

dfFiles = data.frame(matrix(data = c(
  "sample_190612", "FSTL1",
  "sample_729924", "AC002072.1",
  "sample_729924", "AC002070.1,AC004812.1",
  "sample_729794", "ANKRD12,AP000897.1,AP005118.1,AP005227.1",
  "sample_780414", "AC002464.1,AIM1,AK9,AL021326.",
  "sample_780414", "AC002464.4",
  "sample_780414", "AIM2",
  "sample_780388",  "ATP10A,MIR4715"
), ncol = 2, byrow = TRUE  ), stringsAsFactors = FALSE)

colnames(dfFiles) = c("sample", "gene")
# dfFiles

lsSplit = strsplit(x = dfFiles$gene, split = ",")

# create a parent folder
myParent = "sampleParent"
if(!dir.exists(myParent)){dir.create(myParent)}

# create sub folders
for(ctSample in seq_len(nrow(dfFiles))){
  thisSample = dfFiles$sample[ctSample]
  thisPath = paste0(myParent, "/", thisSample)
  if(!dir.exists(thisPath)){dir.create(thisPath)}
  # save files
  for(ctSplit in seq_len(length(lsSplit[[ctSample]]))){
    thisSplit = lsSplit[[ctSample]][ctSplit]
    write.csv(x = 0, file = paste0(thisPath, "/", thisSplit, ".csv"))
  }
}

这是结果图像。

enter image description here