【问题标题】:Sorting arguments from `...` to pass them only to functions they are designed to [duplicate]从`...`中对参数进行排序以仅将它们传递给它们被设计为[重复]的函数
【发布时间】:2016-06-19 19:24:18
【问题描述】:

在我的函数中,我要么从带有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()`

【问题讨论】:

标签: r


【解决方案1】:

感谢评论,我在这个问题中找到了解决方案 - 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);
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2013-07-11
    • 1970-01-01
    • 2013-06-05
    • 2012-05-09
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多