【问题标题】:How to convert data.frame column from Factor to numeric [duplicate]如何将data.frame列从因子转换为数字[重复]
【发布时间】:2015-02-16 04:43:54
【问题描述】:

我有一个data.frame,其类列是Factor。我想将其转换为数字,以便我可以使用相关矩阵。

> str(breast)
'data.frame':   699 obs. of  10 variables:
 ....
 $ class                   : Factor w/ 2 levels "2","4": 1 1 1 1 1 2 1 1 1 1 ...
> table(breast$class)
  2   4 
458 241
> cor(breast)
Error in cor(breast) : 'x' must be numeric

如何将因子列转换为数值列?

【问题讨论】:

  • 这个问题出现得太频繁了,以至于在 SO 上是重复的
  • 最好的答案总是一样的,“阅读?factor

标签: r


【解决方案1】:
breast$class <- as.numeric(as.character(breast$class))

如果您有很多列要转换为numeric

indx <- sapply(breast, is.factor)
breast[indx] <- lapply(breast[indx], function(x) as.numeric(as.character(x)))

另一种选择是在使用read.tableread.csv 读取文件时使用stringsAsFactors=FALSE

以防万一,创建/更改列的其他选项

 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

 breast <- transform(breast, class=as.numeric(as.character(breast)))

【讨论】:

  • 如果案例包括多列,“function(x)” in breast[indx]
  • @CouchTomato 它是一个 lambda 函数或匿名函数,即。动态创建的功能。这里,“x”是来自breast[indx] 列子集的每个列值,这些列值在lapply 中循环。 as.characteras.numeric 需要输入作为向量,这就是我们循环的原因
【解决方案2】:

来自?factor

要将因子 f 转换为近似其原始数值,建议使用as.numeric(levels(f))[f],它比as.numeric(as.character(f)) 效率略高。

【讨论】:

    【解决方案3】:

    这是FAQ 7.10。其他人已经展示了如何将其应用于数据框中的单个列,或数据框中的多个列。但这确实是治标不治本。

    更好的方法是使用read.tablecolClasses 参数和相关函数来告诉R 该列应该是数字的,这样它就不会创建因子并创建数字。这将为任何不转换为数字的值输入NA

    另一个更好的选择是找出为什么 R 不能将该列识别为数字(通常是该列中某处的非数字字符)并修复原始数据,以便正确读取它而无需创建 NAs .

    最好是最后2个的组合,在读入之前确保数据正确并指定colClasses,这样R就不需要猜测了(这也可以加快读取速度)。

    【讨论】:

      【解决方案4】:

      作为$dollarsign 符号的替代,使用within 块:

      breast <- within(breast, {
        class <- as.numeric(as.character(class))
      })
      

      请注意,您需要先将向量转换为字符,然后再将其转换为数字。简单地调用 as.numeric(class) 不会得到每个因子级别 (1, 2) 对应的 id,而是级别本身。

      【讨论】:

        猜你喜欢
        • 2011-02-20
        • 2012-03-04
        • 1970-01-01
        • 1970-01-01
        • 2022-01-02
        • 2018-05-17
        • 2019-12-01
        相关资源
        最近更新 更多