更新R中的函数和变量访问

时间:2015-02-08 22:14:50

标签: r scoping

我需要在函数内更新模型公式。这是一个例子:

A <- runif(n = 200)             #  generate some data
B <- runif(n = 200)
P <- 1/(1+exp(.5-A))            #  generate event probability
outcome <- runif(n = 200) < P   #  generate outcome

my.function <- function(model, data.to.add) {   # this is the function for updating the formula
  new.model <- update(object = model, formula. = ~ . + data.to.add)
  return (new.model)
}

test <- my.function(model = glm(outcome ~ B, family = binomial(link="logit")), data.to.add = A) 

不幸的是,执行此代码会引发如下错误:

Error in eval(expr, envir, enclos) : object 'data.to.add' not found 

似乎my.function无法提供变量data.to.addupdate函数的值。如何为另一个函数中的update函数提供正确的变量范围,我该怎么办?

编辑:好的,如果要传递给要更新的函数的变量在全局环境中,那么你的解决方案是好的,现在如果我必须在函数内部定义变量,由于较少的范围,我再次得到错误变量:

A <- runif(n = 200)             #  generate some data
P <- 1/(1+exp(.5-A))            #  generate event probability
outcome <- runif(n = 200) < P   #  generate outcome

nested.update<-function(model) {
  B<-runif(n = 200)
  my.function <- function(model, data.to.add) {   # this is the function for updating the formula
    data.to.add <- paste('. ~ . +', deparse(substitute(data.to.add)), sep = "")
    new.model <- update(object = model, formula. = data.to.add)
    return (new.model)
  }
  return(my.function(model = model, data.to.add = B))
}

nested.update(model = glm(outcome ~ A, family = binomial(link="logit")))

1 个答案:

答案 0 :(得分:2)

修改

my.function <- function(model, data.to.add) {   # this is the function for updating the formula
  data.to.add <- sprintf('. ~ . + %s', deparse(substitute(data.to.add)))
  new.model <- update(object = model, formula. = data.to.add)
  return (new.model)
}

my.function(lm(mpg ~ wt, data = mtcars), disp)

# Call:
#   lm(formula = mpg ~ wt + disp, data = mtcars)
# 
# Coefficients:
#   (Intercept)           wt         disp  
#      34.96055     -3.35083     -0.01772 

my.function(lm(mpg ~ wt, data = mtcars), hp)

# Call:
#   lm(formula = mpg ~ wt + hp, data = mtcars)
# 
# Coefficients:
#   (Intercept)           wt           hp  
#      37.22727     -3.87783     -0.03177 

答案不好:

由于您要将公式传递给update.formula,因此R发送update.default而不是默认update。参数名称为oldnew。在update.default中,您现在使用的名称为modelformula.

还使用解决方法将正确的变量名称添加到公式

my.function <- function(model, data.to.add) {   # this is the function for updating the formula
  data.to.add <- sprintf('. ~ . + %s', deparse(substitute(data.to.add)))
  new.model <- update(old = model, new = data.to.add)
  return (new.model)
}

my.function(y ~ a, b)
# y ~ a + b
my.function(y ~ a, c)
# y ~ a + c