当argument是一个语言对象时,通过do.call添加ggtitle

时间:2022-09-25 18:44:26

Consider a simple function, which adds a ggtitle to a grob

f <- function(PLOT, TITLE) {
  PLOT + ggtitle(TITLE)
}

Calling the function directly works as expected.
However, calling the function via do.call(f, ..) throws an error when TITLE is a language object

直接调用该函数可以按预期工作。但是,当TITLE是一个语言对象时,通过do.call(f,..)调用该函数会引发错误

## Sample Data
TIT <- bquote(atop("This is some text",  atop(italic("Here is some more text"))))
P   <- qplot(x=1:10, y=1:10, geom="point")

## WORKS FINE
f(P, TIT)

## FAILS
do.call(f, list(P, TIT))
## Error in labs(title = label) : could not find function "atop"

This of course only happens when TIT is a language object

这当然只有在TIT是语言对象时才会发生

TIT.char <- "This is some text\nHere is some more text"
do.call(f, list(P, TIT.char))
## No Error

How can do.call() be used correctly when arguments are language objects?

当参数是语言对象时,如何正确使用do.call()?

1 个解决方案

#1


11  

Use

使用

do.call(f, list(P, TIT), quote=TRUE)

instead. The problem is that your expression is being evaluated when you run do.call. By setting quote=TRUE it will quote the arguments to leave them un-evaluated when passing them along to f. You can also explicitly quote TIT

代替。问题是运行do.call时正在评估表达式。通过设置quote = TRUE,它将引用参数,以便在将它们传递给f时将它们取消评估。您也可以明确引用TIT

do.call(f, list(P, quote(TIT)))

#1


11  

Use

使用

do.call(f, list(P, TIT), quote=TRUE)

instead. The problem is that your expression is being evaluated when you run do.call. By setting quote=TRUE it will quote the arguments to leave them un-evaluated when passing them along to f. You can also explicitly quote TIT

代替。问题是运行do.call时正在评估表达式。通过设置quote = TRUE,它将引用参数,以便在将它们传递给f时将它们取消评估。您也可以明确引用TIT

do.call(f, list(P, quote(TIT)))