Merge together thousands of files in R -- in the right order

I am trying to write a function to bind files together. It is weather data for 50 years, each separated by year, and 75 replicates of every year. I want to bind the files together so that I have a continuous 50 year run. I should end up with 75 50-year runs.

The files are named "clim" then rep ("01" through "99") then 01year ("2014" through "2064"). So clim01012014.txt is my first file. But there are no reps that are multiples of 4.

My thoughts are to import my files as a list

files <- list.files("../Dropbox/APSIM/Climate files")   

then use a function based on rbind to bind together files that have the same reps (that part in the middle, after "clim").

But I am having troubles conceptualizing how to tell R to bind files that have different endings, but the same middle numbers --

rbind(clim01012014.txt, clim01012015.txt, clim01012016.txt, clim01012017.txt, . . .)

Maybe I will need a loop instead of a function?

Answers


Input files:

set.seed(1)
files = sort(paste0('clim', formatC(sample(1:2, 10, T), width = 2, flag = 0), '01', sample(2014:2064, 10)))
files
# [1] "clim01012022" "clim01012024" "clim01012050" "clim01012058" "clim02012030" "clim02012032" "clim02012036" "clim02012046"
# [9] "clim02012047" "clim02012057"

Split by your "rep":

l = split(files, sub('clim(..).*', '\\1', files))
l
#$`01`
#[1] "clim01012022" "clim01012024" "clim01012050" "clim01012058"
#
#$`02`
#[1] "clim02012030" "clim02012032" "clim02012036" "clim02012046" "clim02012047" "clim02012057"

Now you can lapply over that list - smth like:

lapply(l, function(x) do.call(rbind, lapply(x, read.csv)))

I ended up using a loop for this and learning about sprintf. This code binds my files together by the commonality of numbers in the middle of the filename and then writes the bound files out for use in another program.

data <-NULL 
for (i in 1:75){
  for (filename in l[[i]]){
  data <- rbind(data, read.table(sprintf("Bind/%s", filename)) )
  write.csv(file = sprintf("met%s.csv",names(l[i])), data, row.names = FALSE,     
  col.names=FALSE )
  } 
data <- NULL
}

Need Your Help

Access iOS Control Center using appium

ios automation swipe appium control-center

I am trying to open the Control Center using appium and the following code:

C++ password masking

c++ input passwords masking

i'm writing a code to receive password input. Below is my code... the program run well but the problem is other keys beside than numerical and alphabet characters also being read, for example delete,