[R] How to loop on file names
Bretschneider SIG-R
bretschr at xs4all.nl
Tue Jan 17 13:03:23 CET 2012
Dear Hélène Genet,
Re:
> Dear all,
>
> I need to do the same procedure on several files. But I don't know how to refer to the file name.
> Here is an example of what I am trying to do.
>
> List of files: file1(A,B,C, D1...Dn), file2(A,B,C,E1,...,En), file3(A,B,C,F1,...,Fn)
>
> Procedure I want to apply on each file:
>
> dft <- melt(df,id=c('A','B','C'))
> dft$X <- substr(dft$variable,1,3)
> dft$Y <- substr(dft$variable,4,8)
> dft1 <- cast(dft, A+B+C+X ~ Y,value="response")
>
> As you see all the files contains the same 3 variables A,B,C that I use in the procedure.
> So I want to apply the procedure on all the file in a loop.
> Something like :
>
> filelist <- c('file1' , 'file2' , 'file3')
>
> for (i in 1:3) {
> filename <- filelist[i]
> ...
> }
>
> Any suggestion to refer to these files in this loop?
>
> Thanks you in advance,
>
> Helene
>
> --
> Hélène Genet, PhD
> Institute of Arctic Biology
> University of Alaska Fairbanks
> Irving I Blg, Room 402
> Fairbanks AK 99775
>
> Phone: 907-474-5472
> Cell: 907-699-4340
> Email: hgenet at alaska.edu
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
I use this procedure to point to a folder (of WAV files in this example) and process all those files in a loop:
# select FOLDER w. WAV-files
fnam = dirname(file.choose()) # choose any one file from the folder (= directory)
filist = list.files(fnam, recursive=TRUE, pattern="wav")
filist1 = paste(fnam,"/",filist, sep="")
nfiles = length(filist1)
#
# filenames loop ===============================>>>>>>>>>>
for(i in 1:nfiles) {
inname=filist1[i]
ywave=readWave(inname) # read the i'th file (wav as an example, can be any filetype you need)
ywave2=ywave # output is the same as input (yet)
###
### DO ANY PROCESSING YOU WANT HERE to change ywave into ywave2
###
outname=paste(dirname(inname), "/*",basename(inname), sep="")
writeWave(ywave2,outname)
}
I took these few lines out of a larger program with wave file processing not relevant here.
Hope I didn't forget something, and that this works for your case,
Beste wishes,
Franklin Bretschneider
Utrecht University
--
Dept Biologie
Kruytgebouw W711
Padualaan 8
3584 CH Utrecht
The Netherlands
More information about the R-help
mailing list