【问题标题】:Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric even after convert them to numerical variablescolMeans(x, na.rm = TRUE) 中的错误:“x”必须是数字,即使在将它们转换为数字变量之后也是如此
【发布时间】:2021-02-14 19:03:38
【问题描述】:

我几天前刚开始学习R。我正在尝试根据此处的教程(https://www.benjaminbell.co.uk/2018/02/principal-components-analysis-pca-in-r.html#further)在 R 控制台下使用 R(版本 4.0.3)运行 PCA

我的数据由 2 个分类变量 (SPECIES & STATE) 和 4 个数值变量组成,分类变量对我的 PCA 很重要,无法删除。

我将我的 excel 数据 (dataset1.csv) 加载为 dataset2,并尝试使用以下方法将它们转换为数值变量:

#1
d = data.frame(Species=c("EA", "EH", "ES"), x=runif(3), y=runif(3))

#2
d$Species = as.numeric(as.factor(d$Species))

#3
3. d = data.frame(State=c("Kelantan", "Terengganu", "Pahang", "Johor"), x=runif(4), y=runif(4))

#4
d$State = as.numeric(as.factor(d$State))

见教程:Principal Components Analysis:Error in colMeans(x, na.rm = TRUE) : 'x' must be numeric

但是,当我使用代码:p <- prcomp(dataset2) 时,我仍然收到错误:

colMeans(x, na.rm = TRUE) 中的错误:“x”必须是数字

非常感谢帮助我使用分类变量和数值变量运行 PCA。

P/S:我之前曾与 FactorMineR 和 Factoshiny 合作过,但我没有看到可以帮助我将状态标记为不同图标和不同颜色的物种等选项。

【问题讨论】:

  • 您需要发布一个完全可重现的示例。在运行第 1 行和第 2 行后跟 prcomp() 时,我没有收到错误消息。运行 dput(head(dataset2)) 以提供数据集的样本。
  • 删除 dataset2 的因子列,然后运行 ​​prcomp()。例如,如果因子列是 dataset2 中的第 1 列,请尝试运行:prcomp(dataset2[, -c(1)]。如果您有不止一列不是数字的,那么也将这些列子集化。

标签: r pca


【解决方案1】:

我不知道你的问题是什么!我刚刚转换了你所做的,但它有效。请复制并粘贴代码然后运行。它会起作用的。

 d = data.frame(State=c("Kelantan", "Terengganu", "Pahang", "Johor"), x=runif(4), y=runif(4))
> str(d)
'data.frame':   4 obs. of  3 variables:
 $ State: Factor w/ 4 levels "Johor","Kelantan",..: 2 4 3 1
 $ x    : num  0.4941 0.0722 0.206 0.4999
 $ y    : num  0.266 0.177 0.133 0.442
> d$State = as.numeric(as.factor(d$State))
> d
  State          x         y
1     2 0.49413147 0.2664495
2     4 0.07220937 0.1772339
3     3 0.20597378 0.1326426
4     1 0.49994185 0.4415824 
> prcomp(d)
Standard deviations (1, .., p=3):
[1] 1.31234286 0.07598757 0.05476076

Rotation (n x k) = (3 x 3):
             PC1         PC2       PC3
State  0.9837020 -0.04918652 0.1729481
x     -0.1549119 -0.72014961 0.6763038
y     -0.0912835  0.69207314 0.7160322

【讨论】:

    猜你喜欢
    • 2020-12-19
    • 2019-10-04
    • 2018-05-23
    • 2023-03-28
    • 2020-06-18
    • 2017-10-25
    • 2018-01-27
    • 2018-01-17
    • 1970-01-01
    相关资源
    最近更新 更多