2017-05-20 41 views
0

我遵循this教程来创建和可视化PCA。 Im特别感兴趣的部分是为现有模型添加新的数据点。现有PCA模型的新数据点

正如本教程所示,我们将使用predict(ir.pca,newdata = tail(log.ir,2))来预测新的PC。但是,我如何将这些新观察添加到现有的情节?它看起来不像预测函数返回与ggplot函数中使用的ir.pca相同的对象。

我发现了类似的问题herehere但他们计算新的PCA评分并将它们添加到方差图(如果我理解正确的话)。

最终,我后面要看看新点是否落入使用初始数据集定义/导出的置信椭圆内。

我从教程使用的代码:

# log transform 
    log.ir <- log(iris[, 1:4]) 
    ir.species <- iris[, 5] 

  
# apply PCA - scale. = TRUE is highly 
# advisable, but default is FALSE. 
ir.pca <- prcomp(log.ir, 
                 center = TRUE, 
                 scale. = TRUE) 

library(devtools) 
install_github("ggbiplot", "vqv") 
  
library(ggbiplot) 
g <- ggbiplot(ir.pca, obs.scale = 1, var.scale = 1, 
              groups = ir.species, ellipse = TRUE, 
              circle = TRUE) 
g <- g + scale_color_discrete(name = '') 
g <- g + theme(legend.direction = 'horizontal', 
               legend.position = 'top') 
print(g) 

而作为教程提示我想补充其排在同ggplot可视化现有的情节

感谢

新数据
+0

如果您在问题中提供了[可重现的示例](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example),它会更容易帮助您本身。 – MrFlick

+0

@MrFlick更新了 –

回答

1

当我们检查ggplot对象,我们看到它有一个名为data元素:

str(g) 
# List of 9 
# $ data  :'data.frame': 150 obs. of 3 variables: 
# ..$ xvar : num [1:150] -2.41 -2.22 -2.58 -2.45 -2.54 ... 
# ..$ yvar : num [1:150] -0.397 0.69 0.428 0.686 -0.508 ... 
# ..$ groups: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ... 
# $ layers  :List of 5 
# <snip> 

因此,我们可以将新数据点添加到data数据帧。假设从iris这10点意见是我们的“新”的意见,而且我们预测他们的PC值:

set.seed(123) 
x <- sample(seq_len(nrow(iris)), 10) 
predicted <- predict(ir.pca, newdata = log.ir[x, ]) 

我们可以添加这些预测值至data数据帧

g$data <- rbind(g$data, 
    data.frame(
    xvar = predicted[, "PC1"], 
    yvar = predicted[, "PC2"], 
    groups = "new" 
) 
) 

使print(g)产量 enter image description here

+0

感谢您的答案。附加问题仅仅是为了澄清一些事情:使用预测功能来可视化新数据点(就像上面所做的那样),并且从一开始就贯穿整个PCA编译过程(然后将其叠加到现有PCA之上)? –

+0

我不是PCA方面的专家,因此您可能希望在其他地方寻找明确的答案,但我的直觉是,是有区别的,因为如果您在新的PCA上运行PCA,您的主要组件几乎肯定会有所不同数据集(结合“现有”和“新”观察)。 –