从父环境中调用缺少的参数

时间:2019-01-15 17:01:04

标签: r

我找不到从父环境中恢复丢失的参数(或重建它)的聪明方法

使用missing

失败
fooBar <- function(x,y){
  if(missing(y)) {
    y = get0("y", inherits = TRUE)
    x + y
  } else {
    x + y
  }
}
y <- 1
fooBar(x = 2)

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)
相关问题