2016-03-06 50 views
1

在我的函数中,我从fread()的文件中加载表,或者将表保存到write.table()的文件中。这两个函数有一些重叠的参数名称(sep等),而其他函数只针对一个函数。有没有办法将正确的参数从我的函数调用传递给这些函数?从`...`对参数进行排序,只将它们传递给它们设计的函数

# fnDT is filename to seek, inDT is a function call to build a table 
loadOrBuild <- function (fnDT, inDT, ...){ 
    if (file.exists(fnDT)){ # if file is found, then inDT is not evaluated 
    cat('File found:', fnDT, '; will load it instead of building a new table.\n'); 
    return(loadDT(fnDT, ...)); # loadDT() is my wrapper for fread() 
    } else { 
    cat('File not found:', fnDT, '; we\'ll build new table and then save it.\n'); 
    save_DT(inDT, fnDT, row.names=F, ...); # save_DT() is my wrapper for write.table() 
    return(inDT); 
    } 
} 

build.dt <- function(n=10){ 
    return(data.table(test=rep('A',n))) 
} 


my.dt <- loadOrBuild('myfile.txt', build.dt(20), sep='\t') # this works correctly for both loading and saving 

my.dt <- loadOrBuild('myfile.txt', build.dt(20), nrows=10) # this works correctly for loading but raises an error for saving because `nrows` is not an argument for `write.table()` 
+1

也许看到[这](http://stackoverflow.com/questions/30086163/simplest-way-to-create-wrapper-functions )我的问题或链接的副本 – MichaelChirico

+2

确实,该问题基本上回答我的 - http://stackoverflow.com/questions/4124900/is-there-a-way-to-use-two-statements-in-a-function -in-r。感谢您指点! –

回答

2

感谢评论,我在这个问题上找到了解决方案 - Is there a way to use two '...' statements in a function in R?。就我而言,这已经足够了修改功能到以下几点:

loadOrBuild <- function (fnDT, inDT, ...){ 
    nm.load <- c(names(formals(fread)), names(formals(loadDT))); 
    nm.save <- c(names(formals(write.table)), names(formals(save_DT))); 
    dots <- list(...); 
    if (file.exists(fnDT)){ 
    cat('File found:', fnDT, '; will load it instead of building a new table.\n'); 
    return(
     do.call('loadDT', 
       c(
       list(fnInput = fnDT), 
       dots[names(dots) %in% nm.load] 
      ) 
    ) # instead of loadDT(fnDT, ...) 
    ); 
    } else { 
    cat('File not found:', fnDT, '; we\'ll build new table and then save it.\n'); 
    do.call('save_DT', 
      c(list(dtIn=inDT, fnSaveTo = fnDT), 
       dots[names(dots) %in% nm.save]) 
    ) # instead of save_DT(inDT, fnDT, ...); 
    return(inDT); 
    } 
} 
相关问题