我找不到从父环境中恢复丢失的参数(或重建它)的聪明方法
使用missing
fooBar <- function(x,y){
if(missing(y)) {
y = get0("y", inherits = TRUE)
x + y
} else {
x + y
}
}
y <- 1
fooBar(x = 2)
答案 0 :(得分:1)
Maybe this ?
fooBar <- function(x,y){
if(missing(y)) y <- eval.parent(quote(y))
x + y
}
y <- 1
fooBar(x = 2)
# [1] 3
答案 1 :(得分:0)
我找到了这个解决方案,但我对此感到沮丧
fooBar <- function(x,y=NULL){
if(is.null(y)) {
rm(y) # otherwise, get0 recovers NULL :S
y = get0("y", inherits = TRUE)
x + y
} else {
x + y
}
}
y <- 1
fooBar(x = 2)