英文:
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('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'))
答案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 <- 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')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论