-1

I am trying to select some specific directories and read one specific file from each directory.

Here is an example of directories and files

|-out_original
|-----result_file
|-out_20percent_ds
|-----result_file
|-out_40percent_ds
|-----result_file
|-out_60percent_ds
|-----result_file
|-out_80percent_Ds
|-----result_file

Code

setwd("/home/data/proj/")
datatype = c("20","40","60","80","original")
filenames=as.vector(c(0))

for (i in 1:length(datatype))
{
    if(i <= 5){
        filenames[i]=paste0("out_",datatype[i],"percent_ds/")
    }

    else{   
        filenames[i]=paste0("out_",datatype[i])
    }
}

How can I save files in to variables from each directory?

  • I think you mean "save variables into files". What sort of variables do you have, and what sort of file do you want them to be stored in? – Richie Cotton Jul 10 '14 at 10:59
  • What is the problem? Why does a simple write(x, file) (or write.csv or similar) fail? Do you need to create directories (see ? dir.create)? – Martin Jul 10 '14 at 11:15
  • So after some discussion it seems that the problem is reading in multiple tab delimited files. – Richie Cotton Jul 10 '14 at 12:22
  • There's another good duplicate of this here: https://stackoverflow.com/questions/6145118/with-r-loop-over-data-frames-and-assign-appropriate-names-to-objects-created-i – Richie Cotton Jul 10 '14 at 12:27

1 Answers1

1

Try using list.files. If the working directory is the root of the directory you have shown, then something link this will work:

my.files <- 
  list.files(path = "./", pattern = "result_file", 
             full.names = TRUE, recursive = TRUE)

This recursively searches for files with names containing the pattern "result_file" in the path given. The pattern can be any regular expression and only files which match this regular expression are returned.

You can then read your files using something like

ans <- lapply(my.files, read.table)

assuming your data is tabular.

Anders Ellern Bilgrau
  • 9,928
  • 1
  • 30
  • 37