首页 > 解决方案 > 如何正确评估 R 波浪号表达式中的变量

问题描述

我有一个函数 ( col_grob),它调用另一个函数 ( pal_bar),并使用波浪符号表达式,如下所示:

## plots a colour bar with specified colour intervals
pal_bar <- function(cols) {
  cols <- colorRampPalette(cols)(200)
  par(mar = c(0, 0, 0, 0))
  plot(1:200, rep(1, 200), col = cols, pch = 15, cex = 1.1, bty = 'n', xaxt = 'n', xlab = '', yaxt = 'n', ylab = '', main="")
}

## calls pal_bar function to plot the bar as a grob, tilde expression
col_grob <- function(pal) {
  g <- ggplotify::as.grob(~pal_bar(pal))
  grid::grid.draw(g)
}

运行时返回错误“找不到对象'pal'”:

col_grob(pal = c("red", "blue"))

我遇到了资源和类似的问题,但由于对评估规则缺乏了解,我无法解决问题。我尝试了~pal_bar(I(pal)), bquote()function ,并且可能structure(list(), *)但没有足够的知识来正确格式化语法。

我将如何col_grob(pal = c("red", "blue"))为我绘制所需的颜色条? 在此处输入图像描述

标签: rsyntax

解决方案


一个可能的解决方案:

col_grob <- function(pal) {
  txt <- substitute(pal_bar(pal))
  g <- ggplotify::as.grob(as.expression(txt))
  grid::grid.draw(g)
}

col_grob(pal = c("red", "blue"))

推荐阅读