-1

I would like to loop through a vector of directory names and insert the directory name into the read.table function and 'see' the tables outside the loop. I have a vector of directory names:

dir_names <- c("SRR2537079","SRR2537080","SRR2537081","SRR2537082", "SRR2537083","SRR2537084")

I now want to loop through these and read the tables in each directory. I have:

 list.data<-list()

    for(i in dir_names){
     #print(i)
     list.data[[i]] <- read.table('dir_names[i]/circularRNA_known.txt', header=FALSE, sep="\t",stringsAsFactors=FALSE)
    }

but this isn't recognizing dir_names[i]. Do I have to use paste somehow??

zoe
  • 301
  • 3
  • 11
  • 1
    Possible duplicate of [Importing multiple .csv files into R](https://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r) – Maurits Evers Jan 16 '18 at 01:25
  • I thought the aspect of needing to loop over directories made it different. I did think that the use of `paste0` in the two answers was a bit clumsy. It also seemed like that one might better use `file.path` – IRTFM Jan 16 '18 at 02:02

2 Answers2

2

You are right, you need to paste the value. i will also be the list element not a number, so you don't need to call it as dir_names[i] just i

list.data<-list()

for(i in dir_names){
 #print(i)
 list.data[[i]] <- read.table(paste0(i,'/circularRNA_known.txt'), header=FALSE, sep="\t",stringsAsFactors=FALSE)
}

Can I also suggest that (just for your info, if you wanted a more elegant solution) that you could use plyr's llply instead of a loop. It means it can all happen within one line, and could easily change the output to combine all files into a data.frame (using ldply) if they are in consistent formats

list.data.2 <- llply(dir_names, function(x) read.table(paste0(x,"/circularRNA_known.txt"), header=FALSE, sep="\t",stringsAsFactors=FALSE))
Sarah
  • 3,022
  • 1
  • 19
  • 40
  • Wow -thank you SO much. I'm still on the steep part of the learning curve and your shared knowledge is very much appreciated @user2738526 – zoe Jan 16 '18 at 01:32
  • Thanks, if you could accept my answer tif you are happy with it that would be great – Sarah Jan 18 '18 at 05:56
1

dir_names[i] should be used as a variable.

 list.data<-list()

for(i in (1:length(dir_names))){
 #print(i)
 list.data[[i]] <- read.table(paste0(dir_names[i], '/circularRNA_known.txt'), header=FALSE, sep="\t",stringsAsFactors=FALSE)
}
Lavande
  • 744
  • 8
  • 20