Sar*_*rah 5 nested r function parameter-passing
我有一个关于通过 R 中的嵌套函数传递默认参数的一般性问题。我的示例(显然)是对我实际想要做的事情的极大简化,但我在其他时候遇到过这个问题,所以我正在寻找一个通用的解决方案.
基本上我有三个函数,并且希望某些元素在所有三个函数中都有一个默认值。这些函数在彼此内部调用,但有时单独foo1调用(即调用foo2和foo2调用foo3,但有时我只调用foo3或foo2)。
编辑以澄清:我正在寻找一种方法来wd从被调用的函数级别传递(在我的实际问题中)一些其他变量,而不必在每个函数调用中将它们写出来。那就是我想wd在所有级别设置默认值。为了避免将它们命名为所有不同的东西,如果您想单独调用我wd = wd在每个函数调用中尝试使用的函数(旨在wd从它正在调用的函数中访问它),这会造成混淆。这给了promise already under evaluation: recursive default argument reference or earlier problems?. 有没有更好的方法来传递参数通过以便在另一个函数中调用时它传递参数?
我的第一个示例作品显示了工作代码,但是每次我调用其他函数时,我都必须指定它wd = wd,当它是多个参数时,我多次/在其中调用函数ddply使脚本使用起来很麻烦.
第二个例子是我所希望的,wd默认情况下wd在它被调用的环境中设置为where ,但这显然不允许发生错误。传递参数而不必不断分配参数的最佳方法是什么?
编辑:我已经查看了promise 已经在评估中的答案:递归默认参数引用或早期问题?并且我知道这是一种可能的解决方法(它是我目前运行脚本的方式),但我真的希望每个函数的参数都具有相同的名称,以便在单独调用它们时既快速又简单记住参数名称。
示例 1:工作正常,但没有设置默认值。
foo1 <- function(x, wd, reps){
filename = paste0("Event", x)
myString <- foo2(file = filename, wd = wd)
rep(myString, reps)
}
foo2 <- function(file,wd){
filePath <- file.path(wd,file)
foo3(Path = filePath, wd = wd)
}
foo3 <- function(Path, wd){
paste("Absolute File path is:", Path, "Current working Dir is:", wd)
}
foo1(1, wd = "c:/temp", 2)
foo2("C:/temp/otherfilename")
Run Code Online (Sandbox Code Playgroud)
示例 2:
foo2 <- function(file,wd){
filePath <- file.path(wd,file)
foo3(Path = filePath)
}
foo3 <- function(Path, wd=wd){
paste("Absolute File path is:", Path, "Current working Dir is:", wd)
}
foo1(1, wd = "c:/temp", 2)
> Error in paste("Absolute File path is:", Path, "Current working Dir is:", :
promise already under evaluation: recursive default argument reference or earlier problems?
Run Code Online (Sandbox Code Playgroud)
我认为您不应该尝试在不同环境中重复使用相同的名称。在已经评估的 Promise中构建一个可能重复的问题:递归默认参数引用还是早期的问题?以及http://adv-r.had.co.nz/Environments.html#function-envs的一些解释:
为什么不在每个函数中使用单独的名称,如下所示:
foo1 <- function(x, wd. = wd, reps){
filename = paste0("Event", x)
myString <- foo2(file = filename, wd.. = wd.)
rep(myString, reps)
}
foo2 <- function(file, wd.. = wd){
filePath <- file.path(wd.., file)
foo3(Path = filePath)
}
foo3 <- function(Path, wd... = wd){
paste("Absolute File path is:", Path, "Current working Dir is:", wd...)
}
Run Code Online (Sandbox Code Playgroud)
编辑以回应评论讨论。下面的代码可能会更好地实现您的意图并与您的测试调用一起foo1(1, wd = "c:/temp", 2)使用foo2("C:/temp/otherfilename"):
foo1 <- function(x, ..., reps){
filename = paste0("Event", x)
myString <- foo2(file = filename, wd = wd)
rep(myString, reps)
}
foo2 <- function(file, ...){
filePath <- file.path(wd, file)
foo3(Path = filePath)
}
foo3 <- function(Path, ...){
paste("Absolute File path is:", Path, "Current working Dir is:", wd)
}
Run Code Online (Sandbox Code Playgroud)