Natalie
Natalie

Reputation: 21

What does "Error: Must use a vector in `[`, not an object of class matrix." mean when running a PCA?

I am quite new to R and I am trying to run a PCA for an incomplete data set with the code:

res.comp <- imputePCA(questionaire_results_PCA, ncp = nb$ncp)

but R tells me:

Error: Must use a vector in [, not an object of class matrix. Run rlang::last_error() to see where the error occurred.

So I run:

rlang::last_error()

R says:

 1. missMDA::imputePCA(questionaire_results_PCA, ncp = nb$ncp)
 4. tibble:::`[.tbl_df`(X, !is.na(X))
 5. tibble:::check_names_df(i, x)
Run `rlang::last_trace()` to see the full context

So I run:

rlang::last_trace()

And R Says:

Must use a vector in `[`, not an object of class matrix.
Backtrace:
    █
 1. └─missMDA::imputePCA(questionaire_results_PCA, ncp = nb$ncp)
 2.   ├─base::mean((res.impute$fittedX[!is.na(X)] - X[!is.na(X)])^2)
 3.   ├─X[!is.na(X)]
 4.   └─tibble:::`[.tbl_df`(X, !is.na(X))
 5.     └─tibble:::check_names_df(i, x)

Does anyone know what this means and how I could get it to work?

I have run: dput(head(questionaire_results_PCA))

and I got:

structure(list(Active = c(6, 6, 5, 7, 5, 6), `Aggressive to people` = c(NA, 
4, NA, 2, NA, 1), Anxious = c(NA, 4, NA, 3, NA, 2), Calm = c(NA, 
5, NA, 5, NA, 6), Cooperative = c(7, 6, 7, 6, 6, 6), Curious = c(7, 
2, 7, 7, 7, 6), Depressed = c(1, 3, 1, 1, 1, 1), Eccentric = c(1, 
3, 1, 4, 1, 4), Excitable = c(5, 2, 5, 5, 4, 4), `Fearful of people` = c(1, 
2, 1, 2, 1, 1), `friendly of people` = c(5, 6, 7, 7, 7, 7), Insecure = c(2, 
5, 2, 3, 2, 2), Playful = c(4, 6, 2, 5, 6, 6), `Self assured` = c(7, 
6, 7, 5, 6, 6), Smart = c(6, 2, 7, 5, 7, 3), Solitary = c(4, 
4, 3, 4, 3, 2), Tense = c(1, 2, 1, 3, 1, 2), Timid = c(2, 2, 
2, 2, 2, 2), Trusting = c(6, 6, 6, 6, 6, 6), Vigilant = c(7, 
6, 5, 3, 5, 3), Vocal = c(2, 7, 1, 6, 1, 7)), row.names = c(NA, 
-6L), class = c("tbl_df", "tbl", "data.frame"))

I then ran the code: dput(nb$ncp)

and got: 3L

Upvotes: 1

Views: 965

Answers (1)

StupidWolf
StupidWolf

Reputation: 46898

Here's the answer in case anyone comes across the same issue. Using the data provided by OP:

 class(questionaire_results_PCA)
[1] "tbl_df"     "tbl"        "data.frame"

The input of imputePCA requires a data.frame, but it does not work with a tribble. So we need to convert it back to a matrix or data.frame:

library(missMDA)
res.comp <- imputePCA(data.frame(questionaire_results_PCA), ncp = 2)

Error in eigen(crossprod(t(X), t(X)), symmetric = TRUE) : 
  infinite or missing values in 'x'

I get this error because it's a subset of the data and some of the columns have no deviation, we work around this first.

sel = which(apply(questionaire_results_PCA,2,sd)!=0)

# returns you a data.frame
res1 <- imputePCA(as.data.frame(questionaire_results_PCA[,sel]), ncp = 2)
# returns you a matrix
res2 <- imputePCA(as.matrix(questionaire_results_PCA[,sel]), ncp = 2)

Upvotes: 1

Related Questions