Search code examples
rfunctionarguments

How can I omit repeated parameters in functions?


I have a function f2 with a few arguments, and it is repeatedly used as shown below:

f2('data1.csv', par1='x', par2='y', par3='z')
f2('data2.csv', par1='x', par2='y', par3='z')
f2('data3.csv', par1='x', par2='y', par3='z')

Is there a way to code this part - par1='x', par2='y', par3='z' - without typing it out for every function call?

In a particular case the function paste has default sep=" ". I know I can suppress this by setting sep parameter as shown below:

formals(paste)$sep <- ""
print(paste('foo','spam'))

But this might not work for all parameters. I tried to set the given format of date, but this leads to an error:

formals(as.POSIXct)$format <- "%d.%m.%Y"
print(as.POSIXct('3.12.2022'))

Solution

  • The best you could do is define a new function that only takes the file or a function with default parameters:

    f3 <- function(dat_file){
       f2(dat_file, par1='x', par2='y', par3='z')
    }
    
    f3('data1.csv')
    f3('data2.csv')
    f3('data3.csv')
    

    f4 <- function(dat_file, par1='x', par2='y', par3='z'){
       f2(dat_file, par1 = par1, par2 = par2, par3 = par3)
    }
    
    f4('data1.csv')
    f4('data2.csv')
    f4('data3.csv')