[R] building formula objects
Bill.Venables@cmis.csiro.au
Bill.Venables at cmis.csiro.au
Tue Jul 9 14:33:41 CEST 2002
In response to a query from Russel Senior, Jon Baron writes:
> -----Original Message-----
> From: Jonathan Baron [mailto:baron at cattell.psych.upenn.edu]
> Sent: Tuesday, July 09, 2002 9:38 PM
> To: Russell Senior
> Cc: r-help at stat.math.ethz.ch
> Subject: Re: [R] building formula objects
>
> On 07/09/02 03:48, Russell Senior wrote:
> >
> >I want to write a function to take an argument as the response
> >variable of a linear model, e.g. to do anova's across a list of
> >variables, something like the following (except, of course, this
> >doesn't work):
> >
> > function(x) { anova(lm(x ~ my.factor,data=my.data)) }
> >
> >The x in lm() above is getting evaluated at the wrong level. How
> >can I make this work?
>
> I don't know. But what I do instead is this:
>
> my.coeffs <- matrix(NA,mynumber,3) # set up empty matrix
> for (i in 1:my.number) {
> mycoeffs[i] <- as.numeric(try(coef(lm(Y[i]~X1[i]+X2[i]+X3[i]))[2:4]))}
>
> The "try()" is in case it doesn't work for a given value of i
> (e.g., too many missing data), and that makes "as.numeric()"
> necessary. The coef() extracts the coefficients, excluding the
> constant,, which is all I was interested in, but you could store
> the whole thing if you use a list instead of my.coeffs.
>
> I would like to know how to do it with a function.
[WNV] It's not too bad, but a little trickier than most people would
expect. See the Programmer's Niche article in the latest edition of R news
for a general strategy for handling this kind of problem (at the risk of
touting my own stuff).
Bill Venables
> Jon
> --
> Jonathan Baron, Professor of Psychology, University of Pennsylvania
> R page: http://finzi.psych.upenn.edu/
>
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
-.-
> r-help mailing list -- Read
http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
> Send "info", "help", or "[un]subscribe"
> (in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
>
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._.
_._
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list