[R] Getting lm() to work with a matrix

Luc Villandre villandl at dms.umontreal.ca
Wed May 20 15:58:41 CEST 2009

MikSmith wrote:
> Hi
> I'm fairly new to R and am trying to analyse some large spectral datasets
> using stepwise regression (fairly standard in this area). I have a field
> sampled dataset, of which a proportion has been held back for validation. I
> gather than step() needs to be fed a regression model and lm() can produce a
> multiple regression. I had thought something like:
> spectra.lm <- lm(response[,3]~spectra.spec[,2:20])
> might work but lm() doesnt appear to like being fed a range of columns. I
> suspect Ive missed something fairly fundamental here.....
> Any help much appreciated
> best wishes
> mike
Hi Mike,

Indeed, functions like /lm()/ require the object fed to the /data/ 
argument to be either a list, a data frame or an environment containing 
the variables in the model.  The /formula/ argument will then refer to 
column names or element names.

In your situation, I suggest you typecast your matrix into a data frame 
using /as.data.frame()/. You can attribute column names by using 
/colnames()/. If you have a very large number of columns and you don't 
feel like giving them names individually, using the /paste()/ function 
should save you a lot of time.

Also, character-type objects can be typecasted using /as.formula()/ to 
formula-like objects. So, using a combination of /paste()/ and 
/as.formula()/ might make your life a lot easier.

*Luc Villandré*
McGill University Health Center -
Montreal Children's Hospital Research Institute/

More information about the R-help mailing list