好的,假设我用我的函数创建了一个非常简单的直方图:
"ns" : "base.copy",
"size" : 1175058343.0,
"count" : 576578,
"avgObjSize" : 2037,
"storageSize" : 355389440
我的直方图标题显示hist(my.fun(100))
。这对我来说完全没问题!我喜欢R自动识别Histogram of my.fun(100)
并将其放在标题和标签中的方式。
然后我做复杂的计算,说:
my.fun(100)
这一次,标题显示n <- my.complex.algo.that.compute.size(args)
hist(my.fun(n))
。这没有给出Histogram of my.fun(n)
有多大的线索。我知道n
将被评估为某个整数,假设对于此次运行n
,我希望看到直方图的标题显示为n == 42
。
这可能没有自己指定标题(没有Histogram of my.fun(42)
)。我试过这些并且失败了:
main=paste(...)
答案 0 :(得分:3)
如果你将直方图的东西限制为单个参数n的函数,那么你可以这样做:
nhist = function(f,n){
hist(f(n),
main=paste0(
"Histogram of ",
deparse(substitute(f), 500),"
(",n,")", collapse = "\n"))}
你的调用方式略有不同:
Z=100
nhist(runif, Z)
您必须单独传递f
和n
,因为hist
无法确定传递给f
的内容。
答案 1 :(得分:0)
在我查找并学习hist
源代码后,我可以说当hist
被称为顶级函数时,这是不可能的。由于源代码中的这一行:
xname <- paste(deparse(substitute(x), 500), collapse = "\n")
deparse(substitute(x))
尝试捕获(尚未评估)表达式树并将其转换为字符串。这意味着我输入的任何表达式作为hist
函数的第一个参数,它将立即变为一个字符串而不进行任何评估。
为了达到这个目的,我需要在表达式树的某个叶子上强制进行评估。哪个(幸运的是,我只是了解它)可以使用substitute
完成,并使用do.call
将评估的表达式树作为hist
函数的参数传递:
n <- my.complex.algo.that.compute.size(user.args) # suppose this calc return 42
evaluated.arg <- substitute(my.fun(x), list(x=n)) # now this will be my.fun(42)
do.call(hist, list(evaluated.arg))