修改函数内的点(...)

Pie*_*nte 9 r

我正在尝试修改自定义函数中的点(...).这是我的plot2函数的简化示例,它在屏幕上显示一个图type="p"(默认值)并保存一个svg type="l".当其中一个...绘图选项已在函数中时,问题就会浮现.在此示例中,"type"由多个实际参数匹配.

plot2 <-function(...){
plot(...) #visible on screen

svg("c:/temp/out.svg") #saved to file
plot(...,type="l")
dev.off()
}

#This works
plot2(1:10)
#This does not work because type is redefined
plot2(1:10, type="o")
Run Code Online (Sandbox Code Playgroud)

我试图将点list放在函数内部并修改它,但plot不接受列表作为输入.

#Does not work
plot2 <-function(...){
plot(...)

dots <<-list(...)
print(dots)
if("type" %in% names(dots)) dots$type="l"
print(dots)

svg("c:/temp/out.svg")
plot(dots)
dev.off()
}
plot2(1:10, type="o")
Error in xy.coords(x, y, xlabel, ylabel, log) : 
  'x' is a list, but does not have components 'x' and 'y'
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 12

如果您想要转发修改后的版本...,您需要做两件事:

  1. 抓住
  2. 通过转发捕获的点do.call.

其工作原理如下:

plot2 = function (...) {
    # capture:
    dots = list(...)

    # modify:
    dots$type = 'l'

    # forward call:
    do.call(plot, dots)
}
Run Code Online (Sandbox Code Playgroud)

一般来说,do.call(f, list(‹…›))相当于f(‹…›).