如何在函数中省略重复的参数?

huangapple go评论60阅读模式
英文:

How can I omit repeated parameters in functions?

问题

以下是翻译好的部分:

我有一个带有几个参数的函数f2,并且如下所示反复使用它:

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')

有没有办法在每次函数调用时编写这部分 - par1='x', par2='y', par3='z' - 而无需重复键入它?

在特定情况下,函数paste具有默认的sep=" "。我知道可以通过设置sep参数来取消这个选项,如下所示:

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

但这可能对所有参数都不起作用。我尝试设置给定日期的格式,但这会导致错误:

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

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

f2(&#39;data1.csv&#39;, par1=&#39;x&#39;, par2=&#39;y&#39;, par3=&#39;z&#39;)
f2(&#39;data2.csv&#39;, par1=&#39;x&#39;, par2=&#39;y&#39;, par3=&#39;z&#39;)
f2(&#39;data3.csv&#39;, par1=&#39;x&#39;, par2=&#39;y&#39;, par3=&#39;z&#39;)

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

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

formals(paste)$sep &lt;- &quot;&quot;
print(paste(&#39;foo&#39;,&#39;spam&#39;))

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 &lt;- &quot;%d.%m.%Y&quot;
print(as.POSIXct(&#39;3.12.2022&#39;))

答案1

得分: 2

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')
英文:

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

f3 &lt;- function(dat_file){
   f2(dat_file, par1=&#39;x&#39;, par2=&#39;y&#39;, par3=&#39;z&#39;)
}

f3(&#39;data1.csv&#39;)
f3(&#39;data2.csv&#39;)
f3(&#39;data3.csv&#39;)

f4 &lt;- function(dat_file, par1=&#39;x&#39;, par2=&#39;y&#39;, par3=&#39;z&#39;){
   f2(dat_file, par1 = par1, par2 = par2, par3 = par3)
}

f4(&#39;data1.csv&#39;)
f4(&#39;data2.csv&#39;)
f4(&#39;data3.csv&#39;)

huangapple
  • 本文由 发表于 2023年5月30日 06:22:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76360618.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定