Baoqiang,

Here's an approach that should work:
(1) Make sure that the column names of trainx and testx are the same.
(2) Combine trainy and trainx into a data frame for fitting the model.
(2) Use the newdata= argument in the predict() function.
(3) Convert testx from matrix to data frame.

# some example data
nrow <- 5
ncol <- 3
colnames <- paste("x", seq(ncol), sep="")
nrow2 <- 8
trainx <- matrix(rnorm(nrow*ncol), ncol=ncol, dimnames=list(NULL, 
colnames))
trainy <- matrix(rnorm(nrow), ncol=1, dimnames=list(NULL, "y"))
testx <- matrix(rnorm(nrow2*ncol), ncol=ncol, dimnames=list(NULL, 
colnames))

# create data frames for model fitting and prediction
traindf <- data.frame(cbind(trainy, trainx))
testdf <- data.frame(testx)

# fit the model and make predictions for new data
fit <- lm(y ~ ., data=traindf)
py <- predict(fit, newdata=testdf)

Note that the lm() function you fit to the two matrices worked just fine
        lm(trainy ~ trainx)
but the way that names are assigned to the predictor variables
        trainxx1, trainxx2, etc
makes it inconvenient in predicting on new data.

Jean

 

Baoqiang Cao <bqcaom...@gmail.com> wrote on 10/10/2012 09:35:47 AM:
> 
> Hi,
> 
> I have a question about using lm on matrix, have to admit it is very
> trivial but I just couldn't find the answer after searched the mailing
> list and other online tutorial. It would be great if you could help.
> 
> I have a matrix "trainx" of 492(rows) by 220(columns) that is my x,
> and trainy is 492 by 1. Also, I have the newdata testx which is 240
> (rows) by 220 (columns). Here is what I got:
> 
> py <- predict(lm(trainy ~ trainx ), data.frame(testx))
> Warning message:
> 'newdata' had 240 rows but variable(s) found have 492 rows
> 
> The fitting formula I intended is: trainy ~ trainx[,1] + trainx[,2] +
> .. +trainx[,220].
> 
> Any help, please?
> 
> Best,
> Baoqiang

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to