ebb
ebb

Reputation: 274

r automatically modify batch files

I need to sequentially run model that uses several site-specific input files, creates an output data file for each site, moves the output files to a results folder and erases the previous input files leaving it ready for the next run.

I use the windows batch file below for the runs. At the moment I have to manually modify paths and file names for each site. Since I want to run it sequentially through different sites, it would be great to modify it so input and output files and paths would be set automatically feeding from a .csv that has all the information for each site.

Is it possible to create an R code to develop all the .bat files automatically and load them sequentially?

@REM  Remove old output files
erase *.bin
erase *.lis
erase *.out

copy "C:\Users\fix\site7_fix.100" "C:\Users\fix.100"
copy "C:\Users\sitepar\site7_sitepar.in" "C:\Users\sitepar.in"
copy "C:\Users\sch\sch1_spinup\site7.sch" "C:\Users\."
copy "C:\Users\wth\site7.wth" "C:\Users\site.wth"
copy "C:\Users\soils_in\site7_soils.in" "C:\Users\soils.in"
copy "C:\Users\site\site7.100" "C:\Users\site.100"

@REM  Run the spinup simulation
erase *.log

model_mlp -s site7 -n site7_spin > site7_spin_log.txt
model_mlp_list100 site7_spin site7_spin outvars.txt

copy site7_spin.lis "C:\Users\output\spinup\vveg_spin.txt"
@REM copy summary.out   "C:\Users\output\spinup\site7_summary_spin.txt"
copy site7_spin_log.txt "C:\Users\logs\site7_spin_log.txt"
@REM copy methane.out   "C:\Users\output\spinup\site7_spin_ch4.txt"

erase site.100
erase site.wth
erase site7_spin.sch
erase *log*

Alternatively, is it possible to directly modify the batch file to run through the different sites sequentially?

Upvotes: 0

Views: 265

Answers (1)

Ian Wesley
Ian Wesley

Reputation: 3624

Here is a generic example of how you would create a batch file from a data frame, which could be read in from a csv file.

df <- data.frame(MyParamater1 = c('This.bat', 'That.bat'),
           MyParamater2 = c('Thing1', 'thing2'),
           stringsAsFactors = F)


for (i in 1:length(df$MyParamater1)) {
  fileConn <- file(df$MyParamater1[i])
  writeLines(c("Hello",
               paste0("Change to", df$MyParamater2[i]), " Site7"), fileConn)
  close(fileConn)
}

As an alternative you could also read an existing file and replace values. Here is a generic example:

#Read File in
fileConn <- file("This.bat")
myNewBat <- readLines(fileConn)
close(fileConn)

#Replace Values
myNewBat <- gsub("Site7", "Site8", myNewBat)

#Write new file
fileConn <- file("MyNewBat.bat")
writeLines(myNewBat, file("fileConn"))
close(fileConn)

Then you can execute your batch file directly from R:

shell.exec("MyNewBat.bat")

Upvotes: 2

Related Questions