32

I am using the function prcomp to calculate the first two principal components. However, my data has some NA values and therefore the function throws an error. The na.action defined seems not to work even though it is mentioned in the help file ?prcomp

Here is my example:

d <- data.frame(V1 = sample(1:100, 10), V2 = sample(1:100, 10))

prcomp(d, center = TRUE, scale = TRUE, na.action = na.omit)

d$V1[5] <- NA
d$V2[7] <- NA

prcomp(d, center = TRUE, scale = TRUE, na.action = na.omit)

I am using the newest R version 2.15.1 for Mac OS X.

Can anybody see the reason while prcomp fails?

Here is my new example:

d <- data.frame(V1 = sample(1:100, 10), V2 = sample(1:100, 10))

result <- prcomp(d, center = TRUE, scale = TRUE, na.action = na.omit)

result$x

d$V1[5] <- NA

result <- prcomp(~V1+V2, data=d, center = TRUE, scale = TRUE, na.action = na.omit)

result$x

is it possible to retain row 5 in PC1 and PC2? In my real data set I have of course more than two columns of variables and only some of them are missing and I do not want to lose the remaining information hidden in the other values!

user969113
  • 2,349
  • 10
  • 44
  • 51

2 Answers2

33

Another solution if you're not willing to use formula interface is

prcomp(na.omit(d), center = TRUE, scale = TRUE)

which consist of applying na.omit directly to the data frame.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • Thanks for your solution as well. I just realised that using na.omit results in less principal components. I just edited my example above. – user969113 Aug 22 '12 at 18:01
31

Yeah, it looks like a "feature" (bug) that na.action is completely ignored unless you use the formula interface. This has been brought up before on the R Development list.

I think that this should be documented or flagged as a bug.

Just to be clear, this would work because it accesses the formula interface:

prcomp(~V1+V2, data=d, center = TRUE, scale = TRUE, na.action = na.omit)
nograpes
  • 18,623
  • 1
  • 44
  • 67
  • Ok fantastic. Thanks for the formula approach! – user969113 Aug 22 '12 at 17:47
  • 2
    I agree that it should be documented (I'm the author of the query on the R development list); the best way to push this forward, if someone wanted to, would be to propose a change to the documentation and submit it to the r-devel list (and/or the R bug tracker). – Ben Bolker Aug 22 '12 at 18:06