[R] building formula objects

Jonathan Baron baron at cattell.psych.upenn.edu
Tue Jul 9 13:38:22 CEST 2002

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.

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

More information about the R-help mailing list