[R] using a personal template for new R scripts

Steve Taylor steve.taylor at aut.ac.nz
Thu Feb 28 23:40:50 CET 2013

Does anyone know if there's an easy facility to create and specify a template file to be used for new R scripts?

I found myself creating this function which works well (in RStudio on Windows).

newR = function(filename=tempfile(tmpdir='.',fileext='.R'), open=TRUE) {
  template = paste(Sys.getenv('R_USER'), 'R_template.R', sep='/')
  lines = readLines(template)
  lines = sub('Sys.time', format(Sys.time(), '%A, %d %B %Y'), lines)
  lines = sub('getwd', getwd(), lines)
  lines = sub('R.version.string', R.version.string, lines)
  writeLines(lines, filename)
  if (open) shell.exec(filename)

Rather than the default of an empty file, it would be good practice to start with a structured template script.  Such a template might contain opening comments (author, date, project folder, aims, inputs, outputs etc.) and section comment headings for the various components of what a script does (load packages, get data, process data, produce outputs).


More information about the R-help mailing list