Reputation: 2533
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.
Upvotes: 1
Views: 2133
Reputation: 14872
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
}
Upvotes: 2