1

My files are systemically named and all in the same folder. So I want to take advantage and write a function to read them one by one instead of doing this manually for each one.

The names are stored in this text file:

DF <- read.table(text="       site                column row
1          abs   1259 463
2         adm   1253 460
3        afrm   1258 463", header=T)

I want to write a function to go row by row and do this:

You can see for instance if we apply for the first row:

cor$site is abs so:

   file1=read.table("C:\\Data\\abs.txt",sep = "\t")

cor$column is 1259

cor$row is 463

So

 wf= read.table("C:\\Users\\measurement_ 1259_463.txt", sep =' ' , header =TRUE)

Now I do any calculations with file1 and wf.........

And then go to the second row and so on.

sacvf
  • 2,463
  • 5
  • 36
  • 54
  • 1
    `?file.path()` and `?paste()` might be useful here. – EDi May 13 '15 at 13:17
  • 1
    possible duplicate of [reading multiple csv files in R](http://stackoverflow.com/questions/19655431/reading-multiple-csv-files-in-r) – Backlin May 13 '15 at 13:22
  • 1
    possible duplicate of [consolidating data frames in R](http://stackoverflow.com/questions/9807945/consolidating-data-frames-in-r) – cdeterman May 13 '15 at 13:24
  • 1
    It is not a complete duplicate of the other questions since it also involves some string pasting. I chose to retract my vote for closing. – Backlin May 13 '15 at 13:25

1 Answers1

2

Create a character vector with the file names you want to read and follow the instructions in consolidating data frames in R or reading multiple csv files in R.

files <- data.frame(
    site = paste("C:\\Data\\", DF$site, ".txt", sep=""),
    measurement = paste("C:\\Users\\measurement_", DF$column, "_",
                        DF$row, ".txt", sep=""),
    stringsAsFactors = FALSE)

results <- Map(function(s, m){
    file1 <- read.table(s, sep="\t")
    wt <- read.table(m, sep=' ', header=TRUE)
    # Do stuff
    return(result)
}, files$site, files$measurement)

# Alternatively
results <- vector("list", nrow(files))
for(i in 1:nrow(files)){
    file1 <- read.table(files$site[i], sep="\t")
    wt <- read.table(files$measurment[i], sep=' ', header=TRUE)
    # Do stuff
    results[[i]] <- # result
}
Community
  • 1
  • 1
Backlin
  • 14,612
  • 2
  • 49
  • 81
  • 1
    Put whatever you want to do in the function you send to lapply or do a `for`, but that is a less R:ish solution. – Backlin May 13 '15 at 13:55
  • 1
    Sorry, I didn't catch all the details the first time. What about this then? – Backlin May 13 '15 at 14:57
  • 1
    Just type `result` and you get all of it, or `unlist(result)` to flatten it to a vector. If the result is just a single number each time you can change `Map` to `mapply` or `results <- rep(NA, nrow(files))` before the for loop. – Backlin May 13 '15 at 15:13
  • Ah sorry, forgot to add the `stringsAsFactors` to the `data.frame` call. – Backlin May 18 '15 at 07:39