【问题标题】:Fitting PCA using the model.matrix function in R使用 R 中的 model.matrix 函数拟合 PCA
【发布时间】:2019-02-06 20:33:52
【问题描述】:

所以我正在处理一个涉及泰坦尼克号乘客数据的数据集,您可以找到here

所以我在这里使用提供的火车数据。我想通过使用 model.matrix 函数。

之后,从该数据集中移除 Survived 变量。

从这个矩阵中,我想将 PCA 拟合到上一步中的矩阵,并绘制观察值的分数(仅使用前 2 个维度)并根据幸存变量为它们着色。

我尝试了几种方法,但它似乎不准确,也没有颜色。

 library(readr)
 library(dplyr)
 titanic_train <- read_csv("C:/Users/johnt/Desktop/Statistical Data Mining/HW 1/train.csv")

 titanic_train <- titanic_train %>% 
   select(Survived, Pclass, Sex, Age, SibSp, Parch, Fare, Embarked) %>% 
   mutate(Fare = log(Fare))


 ###### Model Matrix

 mm <- titanic_train %>% 
   select(Pclass, Age, SibSp, Parch, Fare, Survived) 

 titan <- model.matrix(-Survived ~., mm)

 #Clean it up
 titan <- titan[,-1] #remove intercept column
 titan <- scale(titan)
 titan[is.na(titan)] <- 0

 #PCA
 titan2 <-prcomp(titan[,-5], center = TRUE, scale. = TRUE)
 titan2


 plot(titan2$x[,1:2],col=mm$Survived)

【问题讨论】:

    标签: r dplyr pca


    【解决方案1】:

    你试过ggbiplot(titan2)吗?

    当然,如果你这样做了,你将不得不在 prcomp 上运行之前过滤只使用前两列

    您能否举例说明您希望 PCA 的外观如何?

    【讨论】:

    • ggbiplot 不适用于 R 版本 3.5.2 :/ 我实际上不确定这应该是什么样子(这里的研究生试图弄清楚 PCA 是什么)
    • 运行以下命令并再次尝试安装:source("https://bioconductor.org/biocLite.R")biocLite("ggbiplot")
    • 即使我调用 library(ggbiplot) 仍然找不到它
    • 好的,然后尝试下载一个名为 factoextra 的包,它做同样的事情。我实际上更喜欢它而不是 ggbiplot。让我知道它是否适合你
    猜你喜欢
    • 2012-08-04
    • 1970-01-01
    • 2023-03-07
    • 2021-03-01
    • 2021-08-07
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多