[R] Looping through a series of (csv) files

Chuck Cleland ccleland at optonline.net
Sun Jul 15 12:11:18 CEST 2007

Yuchen Luo wrote:
> Dear Colleagues.
> This should be a very common operation and I believe there should be a nice
> way in R to handle it.  I couldn't find it in the manual or by searching
> online. I am wondering if I could ask for some help in this community.
> I have 48 csv files; each stores the data for a specific month. The 48
> corresponding months are consecutively from January, 2001 to December, 2004.
> I name the files A200101, A200102,….., A200112, A200201, ……,etc.
> I want to process file A2000101 and store the result to a new file named
> B200101, process file A200102 and store the result to a new file named
> B200102… …etc.
> I do not want to manually change a little bit of the code to read a
> different file and write to a different file every time. I want the program
> to be able to loop through all the files.
> My question is, how to loop through the 48 files?
> Your help will be highly appreciated!
> Best Wishes
> Yuchen Luo

  This will read each of the 48 csv files, add 50 to the values in each
file, and then write each resulting data frame to its own new file:

for(i in 1:48){
 tempdf <- read.csv(paste("c:/myfolder/raw", i, ".csv", sep=""))
 tempdf.new <- tempdf + 50
             file=paste("c:/myfolder/plus50-", i, ".csv", sep=""),
             sep=",", row.names=FALSE)

rm(list=c("tempdf", "tempdf.new", "i"))

  Of course, you can do something more useful than adding 50.

> 	[[alternative HTML version deleted]]
> ------------------------------------------------------------------------
> ______________________________________________
> R-help at stat.math.ethz.ch 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.

Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894

More information about the R-help mailing list