进行关联时无法强制转换为 table

Cannot coerce to a table when doing correlation

我有一个 33 行的列表数据, 如下:

enter link description here

我使用如下代码创建相关系数:

    mpg.df <- as.data.frame(mpg)

cor(mpg, method = "pearson", use = "complete.obs")

但是,我遇到了同样的错误:

Error in cor(mpg, method = "pearson", use = "complete.obs") : 'x' must be numeric

而我用了typeof(mpg.df),结果还是"list"。

如有任何建议,我们将不胜感激!!!

您的示例数据框可能有一列或多列不是数字。由于您的示例数据框看起来像是 R 中预定义 mtcars 数据框的子集,因此我将按如下方式在 R 中创建此子集。

# Select some columns
mtcars2 <- mtcars[, c("mpg", "cyl", "disp", "hp", "drat", "wt")]

# View the first six rows 
head(mtcars2)
#                    mpg cyl disp  hp drat    wt
# Mazda RX4         21.0   6  160 110 3.90 2.620
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875
# Datsun 710        22.8   4  108  93 3.85 2.320
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215
# Hornet Sportabout 18.7   8  360 175 3.15 3.440
# Valiant           18.1   6  225 105 2.76 3.460

现在看一下结构mtcars2,您可以看到所有列都是数字。

# Show the class of each column
str(mtcars2)
# 'data.frame': 32 obs. of  6 variables:
#   $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
# $ disp: num  160 160 108 258 360 ...
# $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
# $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
# $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...

由于所有列都是数字,因此我们可以使用cor函数进行相关性分析。

# Do correlation analysis
cor(mtcars2)
#             mpg        cyl       disp         hp       drat         wt
# mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.6811719 -0.8676594
# cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.6999381  0.7824958
# disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.7102139  0.8879799
# hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.4487591  0.6587479
# drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.0000000 -0.7124406
# wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.7124406  1.0000000