I want to loop over multiple files and apply a function to them. The problem is that these files are all in different, but similarly named, directories. The pathway pattern is s
Have a look at ?list.files
and ?dir
, e.g.:
files <- list.files("/home/smith", pattern="Family[[:alnum:]]+.txt", recursive=TRUE, full.names=TRUE)
for (currentFile in files) {
olddata <- read.table(currentFile, header=TRUE)
## some code
write.table(newdata, file=sub(pattern=".txt$", replacement="test.txt", x=currentFile))
}
Or:
dirs <- dir("/home/smith", pattern="Family[[:alnum:]]+$")
fileName <- file.path(dirs, paste0(dirs, ".txt"))
testFileName <- file.path(dirs, paste0(dirs, "_test.txt"))
for (i in seq(along=fileName))
olddata <- read.table(fileName[i], header=TRUE)
## some code
write.table(newdata, file=testFileName[i])
}