Skip to content

using update( ) in a function?

4 messages · Mahmood ARAI, Roger D. Peng, Thomas Lumley +1 more

#
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
R>  update(fm1, x1 ~ . -x1,data=df1) 

Call:
lm(formula = x1 ~ x2, data = df1) 

Coefficients:
(Intercept)           x2
    -7.753        3.242 

any idea? 

thanks!
mahmood arai
#
I believe this is bug PR#1861.  Not sure what the workaround is.

-roger
_______________________________
UCLA Department of Statistics
http://www.stat.ucla.edu/~rpeng
On Mon, 21 Apr 2003, Mahmood ARAI wrote:

            
#
On Mon, 21 Apr 2003, Roger Peng wrote:

            
No, the code as given doesn't get as far as that
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
+ ff<-substitute(term~.-term)
+ update(model,ff,data=data)
+ }
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
+ ff<-substitute(x~.-x,list(x=as.name(term)))
+  update(model,ff,data=data)
+ }
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
#
Thank you very much for your suggestion.
mahmood arai
Thomas Lumley wrote: