2013-03-13 143 views
9

我寫了一個函數來繪製圖。我遇到的問題之一是需要生成可重現的圖表。當然,一個解決方案是保存我生成的每個圖的代碼(即,保存我爲函數參數設置的確切值)。不過,我想知道是否有一種方法可以捕獲所有輸入值,包括數據對象等,並將它們保存在列表中並將其作爲輸出返回。一個簡單的方法來做到這一點,我想,如下:R:有沒有辦法捕獲所有的函數參數值

plot.foo <- function(x, main=NULL){ 
    plot(x, main=main) 
    list(data=x, main=main) 
} 

不過,我寫的功能有一堆除了省略號參數參數(見下文),所以我不知道是否有更快速的方式來保存所有的輸入參數值。謝謝!

plot.foo <- function(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10,...){ 
    ... 
} 

回答

15

有各種各樣的功能,可能是有用的:match.callmatch.arg然後有用於提取...參數的具體方法。

plot.foo <- 
    function(x, main=NULL){ 
    cl <- match.call() 
    print(cl) 
    plot(x, main=main) 
    list(data=x, main=main) 
    } 

plot.foo(1) 
## plot.foo(x = 1) 
## $data 
## [1] 1 
## 
## $main 
## NULL 

plot.foo <- 
    function(x, main=NULL, ...){ 
    extras=list(...) 
    print(extras) 

    cl <- match.call() 
    print(cl) 

    plot(x, main=main) # this would actually produce the grapjic 
    list(data=x, main=main, extras=extras) # this returns the arguments as a list 
    } 

plot.foo(1, sthg="z") 
## $sthg 
## [1] "z" 

# You could assign the returned list to a name or you could `save` to a file 
plot.foo(x = 1, sthg = "z") 
## $data 
## [1] 1 
## 
## $main 
## NULL 

也有sys.call函數,其結果可能與deparse返回爲文本。

5

從一開始,讓你的所有情節參數

L <- list(x=data, main="string", ylim=c(0,10)) 

然後繪製使用對象作爲參數集

do.call("plot", L) 

確保保存l對於命名列表以後使用。

工作實施例:

L<-list(x=1:10, y=(1:10)^2, main="Y by X",type="l",xlab="X",ylab="Y") 
do.call("plot",L) 
相關問題