Comment Headers in RStudio Sources

Follow

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 specifying 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)
SELECT 1

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()))
SELECT 1

Screen_Shot_2018-08-28_at_10.44.48_PM.png

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

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

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: https://rstudio.github.io/r2d3
//

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

svg.selectAll('rect')
  .data(data)
  .enter().append('rect')
    .attr('width', function(d) { return d * width; })
    .attr('height', barHeight)
    .attr('y', function(d, i) { return i * barHeight; })
    .attr('fill', 'steelblue');

Comments