Nazer
Nazer

Reputation: 3764

Process all the files in a folder with a loop in R

I need to process all the files in a folder, and the files are named sequentially, so I think it is a good time for a loop. The code to process a single file is simple:

df<-read.table("CLIM0101.WTG", skip = 3, header = TRUE)

df<-df[,-1]
df$year<-2014
df$day<-c(1:365)

write.table(df, "clim201401.txt", rownames = "FALSE")

The 99 files to be read are "CLIM0101.WTG" through "CLIM9901.WTG" and they should be written to "clim201401.txt" through "clim201499.txt". Here's a link to the folder with the files:

https://www.dropbox.com/sh/y255e07wq5yj1nd/4dukOLxKgm

So what is the problem here? I don't understand how to write a loop, and haven't found a great description of how to do so. Previous loop questions have had non-loop answers, but it seems like this time it is really what I need.

Upvotes: 1

Views: 4226

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368241

I do that all the time. The basic idiom is

 files <- list.files(....)    # possibly with regexp
 reslist <- lapply(files, function(f) { ... some expressions on f ... }

You simply need to encode your few steps into something like

 myfun <- function(filename) {
      df<-read.table(filename, skip = 3, header = TRUE)
      df<-df[,-1]
      df$year<-2014
      df$day<-c(1:365)
      newfile <- gsub(".WTG", ".txt", filename_
      write.table(df, newfile, rownames = FALSE)  # don't quote FALSE
 }

and now you use use myfun ie the above becomes

 files <- list.files(....)        # possibly with regexp
 invisible(lapply(files, myfun))

Untested, obviously.

Upvotes: 7

Related Questions