Hi Bill,
Thank you for your help. Since I want to perform a series of
regressions (in fact, I want to use lme instead of lm in my data
analysis, but my last email used lm for simplification) with the same
predictors, I would like to do all of them automatically instead of
manually by re-typing the dependent variable name each time. If we can
do it without loop, that will be great too.
When I ran your code, I got different results from what I expected:
> mydata<- data.frame(x1=1:10, x2=(1:10)^2,
y1=2*(1:10) + (1:10)^2 + rnorm(10),
y2=10*(1:10) + 3*(1:10)^2 + rnorm(10))
> mydata
x1 x2 y1 y2
1 1 1 2.753768 13.18116
2 2 4 9.362209 32.22619
3 3 9 13.504666 56.90398
4 4 16 23.968903 88.43677
5 5 25 36.091774 123.06842
6 6 36 48.724808 167.63793
7 7 49 63.295195 216.56807
8 8 64 79.249965 271.97426
9 9 81 99.071244 332.58214
10 10 100 120.344092 400.98084
> fit
<- lm(as.matrix(mydata[, 3:4]) ~ x1 + x2, mydata)
> output
<- t(coef(fit)[, -1])
> output
[,1] [,2] [,3]
[1,] 1.111728 9.350874 3.060115
> output
# this is what I need:
x1 x2
mod1 2.102024 0.9910637
mod2 9.350874 3.0601154
Have I missed something? Thanks!
Peng
Bill.Venables@csiro.au wrote:
RE: [S] loop over a series regression models
Your
question "How [do I] write a loop to obtain the output?" implies that
you have already decided that you must need a loop. In fact you
don't. Here is how I would obtain your output:
mydata<-
data.frame(x1=1:10, x2=(1:10)^2,
y1=2*(1:10) +
(1:10)^2 + rnorm(10),
y2=10*(1:10) +
3*(1:10)^2 + rnorm(10))
fit <-
lm(as.matrix(mydata[, 3:4]) ~ x1 + x2, mydata)
output <-
t(coef(fm)[, -1])
and
that's it.
Bill
V.
-----Original Message-----
From:
s-news-owner@lists.biostat.wustl.edu [mailto:s-news-owner@lists.biostat.wustl.edu] On Behalf Of Peng Huang
Sent:
Friday, 15 April 2005 1:27 PM
To:
s-news@lists.biostat.wustl.edu
Subject:
[S] loop over a series regression
models
Dear All,
I have a data frame that contains several dependent variables
and independent variables. I would like to save the regression
coefficients after fitting each dependent variables (with the same
independent variables). How to write a loop to do it automatically? For
example, I have
mydata<-
data.frame(x1=1:10, x2=(1:10)^2,
y1=2*c(1:10) +
c(1:10)^2 + rnorm(10),
y2=10*c(1:10) +
3*c(1:10)^2 + rnorm(10))
#
I want to perform the following
mod1<-
summary(lm(y1~x1+x2, data="">
mod2<-
summary(lm(y2~x1+x2, data="">
#
then save the coefficients:
output <-
rbind(mod1, mod2)
Question: how to write a loop to obtain the output?
Thank you for your
help!
Peng Huang
|
|