Search code examples
rrstudiocode-snippets

Using a $ symbol within RStudio snippets without the $ sign being evaluated as a variable creator


When I create an R snippet in RStudio the following case, the $ sign from the snippet variable creates problems when I want a literal $sign to appear for use in my snippet (e.g., mtcars$cyl):

snippet cor_binary
    ltm::biserial.cor(${1:df}\$ ${2:continuous_field}, ${1:df}\$ ${3:binary_field}, use = c("complete.obs"), level = 2)

The above snippet produces an unwanted white space between df & field:

# output
ltm::biserial.cor(df$ continuous_field, df$ binary_field, use = c("complete.obs"), level = 2)

No space in my snippet produces a different problem in the output:

snippet cor_binary
    ltm::biserial.cor(${1:df}\$${2:continuous_field}, ${1:df}\$${3:binary_field}, use = c("complete.obs"), level = 2)

# output
ltm::biserial.cor(df\{2:continuous_field}, df\{3:binary_field}, use = c("complete.obs"), level = 2)

How can I include a $ sign in the context of mtcars$cyl without the snippet


Solution

  • The recommended approach would be to use [[ instead of $:

    snippet test
        ${1:df}[["${2:abc}"]]
    

    Which resolves to:

    df[["abc"]]
    

    If $ must be used here's a hacky way to get it working that takes advantage of the fact that snippets can run code using `r ... ` which can be used to print a zero width element between the escaped $ and the second variable. This probably shouldn't be relied upon though.

    snippet test2
        ${1:df}\$`r ""`${2:abc}
    

    Which resolves to:

    df$abc