2015-02-08 24 views
1

我需要更新函數內部的模型公式。這是一個例子:R中的更新函數和變量訪問

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.add的價值update功能。我可以做些什麼來給另一個函數內的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"))) 

回答

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,因此R正在調度update.formula而不是默認的update.default。參數名稱是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 
+0

我仍然得到一個錯誤:'錯誤的getcall(對象):參數「對象」缺失,沒有default',也許是因爲'model'的參數不是一個「公式」對象,而是一個完整的模型對象(就像我之前的代碼示例中那樣)。我需要**通過完整的模型,而不是簡單的公式,因爲我必須改變它dinamically – 2015-02-08 22:49:26

+0

啊我看到,我的壞。看編輯。相同的意見和原則適用@NicolaDinapoli – rawr 2015-02-08 22:59:19

+0

我添加了一個問題的更新來解決有關在函數內聲明的變量的問題,而不是在全局環境中 – 2015-02-09 12:43:45