[R] thanks! using update( ) in a function?
Mahmood Arai
ma at ne.su.se
Tue Apr 22 09:54:33 CEST 2003
Thank you very much for your suggestion.
mahmood arai
Thomas Lumley wrote:
>On Mon, 21 Apr 2003, Roger Peng wrote:
>
>
>
>>I believe this is bug PR#1861. Not sure what the workaround is.
>>
>>
>
>No, the code as given doesn't get as far as that
>
>
>
>>On Mon, 21 Apr 2003, Mahmood ARAI wrote:
>>
>>
>>
>>>Hello,
>>>
>>>using the function "update()" in the following function
>>>does not work.
>>>
>>># a function for running a model: x1 ~ x2
>>># by updating the original model: fm1 <- lm(y ~ x1 + x2,data=df)
>>># update(fm1, x1 ~ . -x1, data=df) works at the command line
>>># but not in the function below.
>>>
>>>
>>>R> foo <- function(fm,x,df)
>>>+ {
>>>+ update(fm, x ~ . -x,data=df)
>>>+ }
>>>R>
>>>R>
>>>R> df1 <- data.frame(y= 1:10, x1=(1:10)^2, x2=sqrt(1:10)^3)
>>>R> fm1 <- lm(y ~ x1+x2, data=df1)
>>>R>
>>>R> foo(fm1, x1, df1)
>>>Error in eval(expr, envir, enclos) : Object "x" not found
>>>
>>>
>
>The main problem here is that the argument `x' is only going to have the
>*value* of x1, where you need the symbol x1. On top of that,
> update(fm, x ~ . -x,data=df)
>uses the symbol `x' rather than its value, so even if its value were
>correct it wouldn't work.
>
>This works
>
>
>>foo<-function(model,term,data){
>>
>>
>+ ff<-substitute(term~.-term)
>+ update(model,ff,data=data)
>+ }
>
>
>>data(trees)
>>a<-lm(Girth~Height+Volume,data=trees)
>>foo(a,Height,data=trees)
>>
>>
>
>Call:
>lm(formula = Height ~ Volume, data = data)
>
>Coefficients:
>(Intercept) Volume
> 69.0034 0.2319
>
>but is not recommended style, as you are defeating the call-by-value
>semantics of R. A better version is
>
>
>>bar<-function(model,term,data){
>>
>>
>+ ff<-substitute(x~.-x,list(x=as.name(term)))
>+ update(model,ff,data=data)
>+ }
>
>
>>bar(a,"Height",data=trees)
>>
>>
>
>Call:
>lm(formula = Height ~ Volume, data = data)
>
>Coefficients:
>(Intercept) Volume
> 69.0034 0.2319
>
>and you could have versions that allowed `term' to be a quoted name or
>expression rather than a string.
>
> -thomas
>
>
>
More information about the R-help
mailing list