Reputation: 3
I'm currently triggering an R script via a scheduler. Sometimes the R script causes errors (maybe due to input problmens). After each run, I get an r-out file with the history log. That log is super helpful in checking if everything went as planed but unfortunately it gets overwritten every day. My question now is: how can I get a different r-out file each day (e.g. with the date to it)
Best regards and thank you, Phil
Upvotes: 0
Views: 4282
Reputation: 23798
To generate a filename that includes the current date, you could take the output of Sys.Date()
and use paste0
to compose the name of the file including the date.
Maybe something like this:
filename <- paste0("R-out_", Sys.Date(), ".log")
#> filename
#[1] "R-out_2016-08-24.log"
The format of the date can be changed with format()
if this is desired (Thanks to @Konrad for reminding this). For instance, we could use format(Sys.Date(), "%d-%m-%Y")
to obtain the day-month-year form that is typically used, e.g., in Europe:
filename <- paste0("R-out_", format(Sys.Date(), "%d-%m-%Y"), ".log")
We can use sink()
to redirect the console (standard) output of a script to a file. In this case the script could be edited to include a definition of the filename
as described above, followed by the command
sink(filename)
This should be inserted into the script file before anything is displayed in the standard output. Possibly these two lines (the definition of the filename and the sink command) could be placed at the very beginning, but I would recommend using setwd(<pathToMyOutputDirectory>)
first, to specify the output directory. After the sink(filename)
command, any output that would normally be displayed in the console will be stored in the file called according to the character string stored in filename
. At the end of the script it would be good to restore the default setting for the standard output by using sink()
without any parameter (or, equivalently, sink(file = NULL)
).
Upvotes: 3