[R] feedback/question on function update()

Peter Ehlers ehlers at ucalgary.ca
Sat Sep 18 22:17:16 CEST 2010


On 2010-09-18 13:14, Joshua Wiley wrote:
> Hello Ben,
>
> I believe the problem is not strictly update() in the for loop, but
> the formula being passed to update().  The value of "i" changes, but
> its symbol does not, so the second time through its like you overwrite
> the first.  Here is one way around it that works for me:
>
>
> mdat<- matrix(c(1,2,3, 11,23,13, 12,4,8), nrow = 3, ncol=3, byrow=TRUE)
> reg<- lm(mdat[7:9]~1)
> for(i in 1:2) {
>    x<- paste(". ~ . + mdat[", ((i-1)*3 + 1), ":", (i * 3), "]", sep ="")
>    print(x) # just to see it
>    reg<- update(reg, x) #update reg twice
> }
> reg
>
>
> I am guessing this is a simpler example of what you are really trying
> to do, but ff you are not interested in doing anything with reg
> between updates, you might consider just update()ing it once with the
> full model.
>
> Hope that helps,
>
> Josh
>
> P.S. I really tried to implement a suggestion for a better way to
> create formulae by Douglas Bates (see
> http://groups.google.com/group/ggplot2/msg/3169aee8708e5e0c? ), but
> was spectacularly unsuccessful.


Ben is making strange use of mdat in lm(); I would use a data frame.
At least, we should name the columns.

  mdat <- matrix(c(1,2,3, 11,23,13, 12,4,8),
                  nrow = 3, ncol=3, byrow=TRUE)
  colnames(mdat) <- paste("x", 1:3, sep="")

  dat <- as.data.frame(mdat)

Then see if the following gives a suitable hint:

  reg <- lm(x3 ~ 1, data = dat)  ## or: reg <- lm(mdat[,"x3"] ~ 1)
  (fo <- formula(reg))

  for(i in 1:2) {
    x <- as.name(colnames(dat)[i])
    fo <- update(fo, bquote(~ . + .(x)))
    print(fo)
  }

(using update.formula() as illustration)


   -Peter Ehlers

>
> On Sat, Sep 18, 2010 at 9:30 AM, Benjamin Godlove<bgodlove at oberlin.edu>  wrote:
>> Hi,
>>
>> First let me say I am a big fan of R and appreciate all your time and
>> effort.
>>
>> The update() function does not seem to work in a for loop.  Consider the
>> following:
>>
>> mdat<- matrix(c(1,2,3, 11,23,13, 12,4,8), nrow = 3, ncol=3, byrow=TRUE)
>> reg<- lm(mdat[7:9]~1)
>> for(i in 1:2) {
>> reg<- update(reg,.~.+mdat[((i-1)*3 + 1):(i*3)]) #update reg twice
>> }
>> reg # reg should have two independent variables, but it only has one
>>
>>
>>
>> The update() function in conjunction with a for loop will only consider the
>> last update, and not save all the previous ones.  Is there a way around
>> this?
>>
>> I appreciate your time.
>>
>> - Ben Godlove
>>
>>         [[alternative HTML version deleted]]
>>



More information about the R-help mailing list