1

In my function, I either load a table from a file with fread(), or save a table to a file with write.table(). Those two functions have some overlapping parameter names (sep etc) while others are specific to a single function. Is there any way to pass correct parameters from my function call to those functions?

# 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()`
Vasily A
  • 8,256
  • 10
  • 42
  • 76
  • 1
    perhaps see [this](http://stackoverflow.com/questions/30086163/simplest-way-to-create-wrapper-functions) question of mine or the linked duplicate – MichaelChirico Mar 06 '16 at 05:37
  • 2
    indeed, that question essentially answers mine - http://stackoverflow.com/questions/4124900/is-there-a-way-to-use-two-statements-in-a-function-in-r . Thanks for pointing on it! – Vasily A Mar 06 '16 at 07:12

1 Answers1

2

Thanks to the comment, I found a solution in this question - Is there a way to use two '...' statements in a function in R?. In my case, it was enough to modify the function to a following:

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);
  }
}
Community
  • 1
  • 1
Vasily A
  • 8,256
  • 10
  • 42
  • 76