从`...`中排序参数,只将它们传递给它们设计的函数

时间:2016-03-06 05:31:06

标签: r

在我的函数中,我要么使用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 个答案:

答案 0 :(得分: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);
  }
}