[R] Seeking help for outomating regression (over columns) and storing selected output

Liaw, Andy andy_liaw at merck.com
Sat Apr 3 15:21:48 CEST 2004


I'm quite sure there're better ways, but this works for me:

> dat <- data.frame(y=rnorm(30), x1=runif(30), x2=runif(30), x3=runif(30),
+                   group=factor(rep(1:3, each=10)))
> 
> getCoef <- function(dat) {
+     apply(dat[,c("x1","x2","x3")], 2,
+           function(x) lm.fit(cbind(1, x), dat$y)$coefficients[2])
+ }
> clist <- by(dat[,c("y","x1","x2","x3")], dat$group, getCoef)
> cmat <- do.call("rbind", clist)
> cmat
          x1         x2         x3
1 -1.8646962  0.6182181 -1.7859563
2 -1.5031314 -1.0639626 -0.2982066
3 -0.8302013  0.8111539 -1.0372803

HTH,
Andy

> From: Greg Blevins
> 
> 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]]
> 
> 


------------------------------------------------------------------------------
Notice:  This e-mail message, together with any attachments,...{{dropped}}




More information about the R-help mailing list