# [R] Seeking help for outomating regression (over columns) andstoring selected output

Robert W. Baer, Ph.D. rbaer at atsu.edu
Sat Apr 3 15:30:02 CEST 2004

```Here's one simplistic solution, perhaps there are better ones:
#  Make some test data and place in dataframe
x1=rnorm(20)
x2=rnorm(20)
x3=rnorm(20)
x4=as.factor(sample(c("G1","G2","G3"),20,replace=T))
y1=2*x1+4*x2+0.5*x3+as.numeric(x4)+rnorm(20)

df=data.frame(y1,x1,x2,x3,x4)

# Now create the ouput dataframe described
out=data.frame(result=c("Intercept",levels(df\$x4)))
out\$X1=as.numeric(coef(lm(df\$y1~df\$x1+df\$x4)))
out\$X2=as.numeric(coef(lm(df\$y1~df\$x2+df\$x4)))
out\$X3=as.numeric(coef(lm(df\$y1~df\$x3+df\$x4)))

#look at it
df
out

----- Original Message -----
From: "Greg Blevins" <gblevins at mn.rr.com>
To: "R-Help" <r-help at stat.math.ethz.ch>
Sent: Friday, April 02, 2004 9:03 PM
Subject: [R] Seeking help for outomating regression (over columns)
andstoring selected output

> Hello,
>
> I have spent considerable time trying to figure out that which I am about
to describe.  This included searching Help, consulting my various R books,
and trail and (always) error.  I have been assuming I would need to use a
loop (looping over columns) but perhaps and apply function would do the
trick.  I have unsuccessfully tried both.
>
> A scaled down version of my situation is as follows:
>
> I have a dataframe as follows:
>
> ID       Y      x1          x2          x3           usergroup.
>
> Y is a continous criterion, x1-x3 continous predictors, and usergroup is
coded a 1, 2 or 3 to indicate user status.
>
> My end goal is a (dataframe or matrix) with just the regression coef from
each of 12 runs (each x regressed separately on Y for the total sample and
for each usergroup).  I envision output as follows, a three column by four
row dataframe or matrix.
>
>
>                          Y and x1;            Y and x2;         Y and x3.
> Total sample:
> usergroup 1:
> usergroup 2:               (Regression Coefs fill the matrix)
> usergroup 3:
>
> Using 1.8.1
> Windows 2000 and XP
>
> Help would be most appreciated.
>
> Greg Blevins, Partner
> The Market Solutions Group
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help