我正在使用功能 prcomp
计算前两个主成分。但是,我的数据有一些 NA 值,因此该函数会引发错误。即使在帮助文件 ?prcomp
中提到了定义的 na.action ,它似乎也不起作用。
这是我的例子:
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)
我正在为 Mac OS X 使用最新的 R 版本 2.15.1。
任何人都可以看到原因
prcomp
失败?这是我的新示例:
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
是否可以在 PC1 和 PC2 中保留第 5 行?在我的真实数据集中,我当然有两列以上的变量,只有其中一些缺失,我不想丢失隐藏在其他值中的剩余信息!
最佳答案
如果您不愿意使用公式界面,另一种解决方案是
prcomp(na.omit(d), center = TRUE, scale = TRUE)
其中包括申请
na.omit
直接到数据框。
关于即使 NA 是允许的,R 函数 prcomp 也会因 NA 的值而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12078291/