[R] body of non-visible function

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Thu May 5 17:30:30 CEST 2005



Anna Oganyan wrote on 5/5/2005 7:42 AM:
> Hello,
> Is there any possibility in R to see the body of the “non-visible” 
> function, for
> example “princomp”?
> If I do :
> 
>  > methods(princomp)
> 
> so, I get that princomp.default and princomp.formula are non-visible 
> functions and
> body(princomp.default) doesn’t show it.
> 
> In particular, I guess I have a very naïve question…
> I’d like to see how scores calculation is implemented in the function
> princomp. Because when I multiply my data matrix on the matrix of loadings
>  >data.matrix %*% princomp(data.matrix, scores=T)$loadings
> 
> I get different result than just doing
> 
>  >princomp(data.matrix, scores=T)$scores.
> 
> Thanks.
> Anna
> 


Hi Anna,

Use getAnywhere("princomp.default") or stats:::princomp.default. This 
has to do with princomp.default not being exported in the stats package 
NAMESPACE.

As for the difference, the scores are based on centering the columns of 
data.matrix before determining the principal components. For example:

 > X <- as.matrix(USArrests)
 > Xc <- sweep(X, 2, colMeans(X), "-")
 > pc <- princomp(X, scores = TRUE) # inappropriate, see ?princomp
 > str(pc$scores)
  num [1:50, 1:4]  -64.8  -92.8 -124.1  -18.3 -107.4 ...
  - attr(*, "dimnames")=List of 2
   ..$ : chr [1:50] "Alabama" "Alaska" "Arizona" "Arkansas" ...
   ..$ : chr [1:4] "Comp.1" "Comp.2" "Comp.3" "Comp.4"
 > Xl <- Xc %*% loadings(pc)
 > str(Xl)
  num [1:50, 1:4]  -64.8  -92.8 -124.1  -18.3 -107.4 ...
  - attr(*, "dimnames")=List of 2
   ..$ : chr [1:50] "Alabama" "Alaska" "Arizona" "Arkansas" ...
   ..$ : chr [1:4] "Comp.1" "Comp.2" "Comp.3" "Comp.4"
 > sum(abs(Xl - pc$scores))
[1] 4.97999e-12
 >

Finally, "data.matrix" is a function in the base package. I would avoid 
using it as a variable name.

--sundar




More information about the R-help mailing list