【问题标题】:Using a $ symbol within RStudio snippets without the $ sign being evaluated as a variable creator在 RStudio 代码片段中使用 $ 符号,而不将 $ 符号评估为变量创建者
【发布时间】:2021-11-16 09:04:10
【问题描述】:

当我在 RStudio 中创建 R sn-p 以下情况时,当我希望在我的 sn-p 中使用文字 $sign 时,来自 sn-p 变量的 $ 符号会产生问题(例如,mtcars$cyl ):

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

上面的 sn-p 在 dffield 之间产生了一个不需要的空白:

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

我的 sn-p 中没有空格会在输出中产生不同的问题:

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)

如何在没有 sn-p 的情况下在 mtcars$cyl 的上下文中包含 $ 符号

【问题讨论】:

  • 你没有告诉我们什么是“code sn-ps”。这些是 RStudio 中的东西吗? (如果是这样,您应该使用该标签,而不是“r”。)
  • 我已经相应地更新了这个问题。谢谢@user2554330

标签: r rstudio code-snippets


【解决方案1】:

使用反引号:

data.table::data.table(`a$b` = 1)
   a$b
1:   1

【讨论】:

    【解决方案2】:

    推荐的方法是使用[[ 而不是$

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

    解析为:

    df[["abc"]]
    

    如果必须使用$,这是一种让它工作的hacky方法,它利用了sn-ps可以使用`r ... `运行代码这一事实,该代码可用于在转义的$和之间打印零宽度元素第二个变量。不过,这可能不应该被依赖。

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

    解析为:

    df$abc
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多