Comment Headers in RStudio Sources


Starting from RStudio 1.2.937, the following file sources support custom commands while sourcing them: R, D3 and SQL file sources. This is accomplished by specifing a !source or !preview comment header in your source file.

R Sources

R Sources can make use of the !source directive to trigger an R function while sourcing the file. For instance, the following example.R file will print itself after being saved:

# !source print
"Hello World"

The syntax of !source is as follows:

# !source function_name(parameter_1, parameter_2, ...)

In other words, it's just a function call that gets executed after sourcing the file. However, there are two special keywords:

  • .code: The .code keyword gets replaced for the contents of the file as a quoted character string.
  • .file: The .file keyword gets replaced for the shortest path to the currently active source file.

We can make use of this two keywords as follows:

# !source cat(paste0("File: ", .file, " has contents: \n", .code))
"Hello World"

which make use of both keywords to print the following in the R console:

File: RStudio/temp/one-plus-one.R has contents:
# !source cat(paste0("File: ", .file, " has contents: \n", .code))
"Hello World"

SQL Sources

In a similar way, SQL files can be previewed with a similar syntax to sourcing R files. SQL comments start with --; therefore, previewing custom SQL would looks as follows:

-- !preview print(.code)

While the code above is interesting, is not very useful; instead, RStudio adds a previewSql function to launch a new SQL Results panel, combining this with the DBI package, we can preview SQL with ease as follows:

-- !preview previewSql(conn=DBI::dbConnect(RSQLite::SQLite()))


However, to save some key strokes, previewSql() can be ommitted:

-- !preview conn=DBI::dbConnect(RSQLite::SQLite())

D3 Sources

Finally, D3 sources can be commented to preview their contents. The syntax is slightly different and currently only the r2d3 package is supported through the following directive:

// !preview r2d3 data=c(0.3, 0.6, 0.8, 0.95, 0.40, 0.20)
// r2d3:

var barHeight = Math.ceil(height / data.length);

    .attr('width', function(d) { return d * width; })
    .attr('height', barHeight)
    .attr('y', function(d, i) { return i * barHeight; })
    .attr('fill', 'steelblue');