user3091668
user3091668

Reputation: 2310

How to read multiple files in R

I would like to make a loop for reading files. I tried paste0, but it is not working. I wanna to do the above command to files from k=1 until k=10.

{for(k in 1:29){
    exprs.file <- paste0("LRRadjustedextremes0.5kgchr",k,".txt")
    eset <- read.eset(exprs.file="/home/proj/MT_Nellore/R/eBrowser/Adjusted/exprs.file")
    }}

Cheers

Upvotes: 0

Views: 626

Answers (1)

Oscar de Le&#243;n
Oscar de Le&#243;n

Reputation: 2361

An efficient approach is to generate a vector with the file names, and read it into a list using lapply:

# Read listed files
k <- 1:29
path <- '/home/proj/MT_Nellore/R/eBrowser/Adjusted/'
files <- paste0(path, 'LRRadjustedextremes0.5kgchr', k, '.txt')
eset <- lapply(X=files, FUN=read.eset)

If you have the files inside a folder and want to read them all, then this works too:

path <- '/home/proj/MT_Nellore/R/eBrowser/Adjusted/'
files <- list.files(path=path, pattern='.txt')
eset <- lapply(X=files, FUN=read.eset)

Also, if your files are too large to fit into memory consider loading one at a time and extracting only the information you need:

files <- list.files(path=path, pattern='.txt')
data <- lapply(X=files, FUN=function(file)
               {
                 tmp <- read.eset(file)
                 return(tmp$expr)
               })

Upvotes: 2

Related Questions