Reputation: 1
why is this code giving me "incorrect dimension" error?
Upvotes: 0
Views: 225
Reputation: 24790
As @r2evans mentions, the object is most likely of a specially defined class "prcomp".
class(pca)
[1] "prcomp"
You can see that pca
is also a list and you can view the names of the list elements with names()
.
is.list(pca)
[1] TRUE
names(pca)
[1] "sdev" "rotation" "center" "scale" "x"
You can access the contents of those elements with the $
operator.
pca$x
PC1 PC2 PC3 PC4 PC5 PC6 PC7 PC8
Mazda RX4 -0.66422351 1.1734476 -0.20431724 -0.12601751 0.75200784 -0.12506777 -0.42357334 -0.003259165
Mazda RX4 Wag -0.63719807 0.9769448 0.11077779 -0.08567709 0.65668822 -0.06619437 -0.44849307 0.056643244
Datsun 710 -2.29973601 -0.3265893 -0.21014955 -0.10862524 -0.07622329 -0.56693648 0.38612406 -0.202035744
Hornet 4 Drive -0.21529670 -1.9768101 -0.32946822 -0.30806225 -0.24391787 0.08382435 0.03299362 -0.023714111
Hornet Sportabout 1.58697405 -0.8287285 -1.03299254 0.14738418 -0.22270405 0.18280435 -0.05793795 0.152342587
Valiant 0.04960512 -2.4466838 0.11177774 -0.87154914 -0.12574876 -0.23043022 0.22451528 0.098663134
Duster 360 2.71439677 0.3610529 -0.65206041 0.09633337 0.29674234 0.27763557 0.44227307 -0.306373481
Then the subset you tried will work.
pca$x[,1:2]
PC1 PC2
Mazda RX4 -0.66422351 1.1734476
Mazda RX4 Wag -0.63719807 0.9769448
Datsun 710 -2.29973601 -0.3265893
Hornet 4 Drive -0.21529670 -1.9768101
Hornet Sportabout 1.58697405 -0.8287285
Valiant 0.04960512 -2.4466838
Duster 360 2.71439677 0.3610529
Understanding this will help you much in your future of R programing.
Data
pca <- prcomp(mtcars[,c(1:7,10,11)], center = TRUE,scale. = TRUE)
Upvotes: 2