Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

pca - R function prcomp fails with NA's values even though NA's are allowed

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...