gpt4 book ai didi

r - 如何将 data.frame 列从 Factor 转换为数字

转载 作者:行者123 更新时间:2023-12-03 08:59:32 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How to convert a factor to integer\numeric without loss of information?

(11 个回答)


6年前关闭。




我有一个 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

如何将 Factor 列转换为数字列?

最佳答案

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)))

另一种选择是使用 stringsAsFactors=FALSE使用 read.table 读取文件时或 read.csv
以防万一,创建/更改列的其他选项
 breast[,'class'] <- as.numeric(as.character(breast[,'class']))

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

关于r - 如何将 data.frame 列从 Factor 转换为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27528907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com