【问题标题】:Problem with finding covariance matrix for Iris data in R在 R 中查找 Iris 数据的协方差矩阵的问题
【发布时间】:2021-12-15 20:28:09
【问题描述】:

尝试在 R 中查找 Iris 数据的协方差矩阵时,我不断得到 NA。

library(ggplot2)
library(dplyr)

dim(iris)
head(iris)

numIris <- iris %>% 
  select_if(is.numeric)

plot(numIris[1:100,])

Xraw <- numIris[1:1000,]

plot(iris[1:150,-c(5)]) #species name is the 5th column; excluding it here.
Xraw = iris[1:1000,-c(5)] # this excludes the 5th column, which is the species column
#first, to get covariance, we need to subtract the mean from each column

X = scale(Xraw, scale = FALSE)

head(X)

Xs <- scale(Xraw, scale = TRUE)
head(Xs)

covMat  = (t(X)%*%X)/ (nrow(X)-1)
head(covMat)

【问题讨论】:

    标签: r covariance-matrix iris-dataset


    【解决方案1】:

    你有什么不能使用cov(numIris)的原因吗?

    通过尝试选择只有 150 行的矩阵/数据框的 1000 行,最终会得到 850 行充满NA 值的行(尝试tail(Xraw) 来查看)。如果您设置Xraw &lt;- iris[, -5] 并从那里开始,您会得到all.equal(covMat, cov(iris[, -5]))TRUE 的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-04
      相关资源
      最近更新 更多