RStudio Code Snippet - `r expr ` - that is Not Executed

RStudio Code Snippets are text macros that are used for quickly inserting common snippets of code.

If you're not already familiar, here's Mara's walk-through. You can set these up for R, Markdown, Python, Stan, and other langauages and markups

image

You can also run R code in your snippet. Use `r expr` anywhere in your snippet; your R code will be executed when the snippet is expanded, and the result inserted into the document.


A question came up recently, what if I want my snippet to produce the text `r expr` without executing the code?

For example, suppose you want a shortcut to an RMarkdown header that with a date that always produces the current date:

`r format(Sys.time(), "%Y-%m-%d")`

The problem is this:

  • You want to insert some text between backticks
  • A snippet interprets backticks as a signal to evaluate the code

So you need to find a way to insert the backticks in a way that doesn't trigger evaluation.

You can do this by using the following snippet definition:

snippet tod
    `r quote('\u0060r format(Sys.time(), "%Y-%m-%d")\u0060')`

This works because:

  • `r ...` tells the snippet to evaluate the code
  • quote() allow you to define an expression that will be evaluated later
  • \u0060 is the unicode encoding for a backtick

Footnote:

To determine what the unicode encoding for any character is, use the function iconv():

> iconv("`", from = "ascii", toRaw = TRUE)
[[1]]
[1] 60

To convert from unicode to ASCII, again use iconv():

> iconv("\u0060", to = "ASCII")
[1] "`"
2 Likes

My super low-tech solution: I use Alfred snippets for these, e.g.

`r emo::ji("")`

comes up if I'm in RStudio and type r e m j. :grimacing:

1 Like