From murdoch at stats.uwo.ca  Fri Nov 18 15:02:28 2005
From: murdoch at stats.uwo.ca (murdoch@stats.uwo.ca)
Date: Fri, 18 Nov 2005 15:02:28 +0100 (CET)
Subject: [Rd] pr[in]comp: predict single observation when data has
	colnames (PR#8325)
Message-ID: <20051118140228.0353E1DFD0@slim.kubism.ku.dk>

On 11/18/2005 7:04 AM, bhx5 at mevik.net wrote:
> To my knowledge, this has not been reported previously, and doesn't
> seem to have been changed in R-devel or R-patched.
> 
> If M is a matrix with coloumn names, and
> 
> mod <- prcomp(M)  # or princomp
> 
> then predicting a single observation (row) with predict() gives the
> error
> 
> Error in scale.default(newdata, object$center, object$scale) : 
> 	length of 'center' must equal the number of columns of 'x'
> 
> This doesn't happen if M doesn't have coloumn names.
> 
> For instance:
> 
> 
>>M <- matrix(rnorm(30), ncol = 3)
>>mod <- prcomp(M[-1,])
>>predict(mod, newdata = M[1,, drop = FALSE])
> 
>            PC1       PC2       PC3
> [1,] -1.666191 -2.333012 -1.424587
> 
> 
>>colnames(M) <- 1:3
>>mod <- prcomp(M[-1,])
>>predict(mod, newdata = M[1,, drop = FALSE])
> 
> Error in scale.default(newdata, object$center, object$scale) : 
> 	length of 'center' must equal the number of columns of 'x'
> 
> 
> I believe the problem is the line
> 
>         newdata <- newdata[, nm]
> 
> in predict.prcomp (line 106 of prcomp.R) and predict.princomp (line 11
> of princomp-add.R), which should probably be
> 
>         newdata <- newdata[, nm, drop = FALSE]
> 

Yes, I see the problem, and I agree with your correction.  I'll commit a 
patch.  Thanks!

Duncan Murdoch



[Rd] pr[in]comp: predict single observation when data has colnames (PR#8325)
murdoch@stats.uwo.ca