我有一个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
如何将因子列转换为数字列?
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
or read.csv
以防万一,创建/更改列的其他选项
breast[,'class'] <- as.numeric(as.character(breast[,'class']))
or
breast <- transform(breast, class=as.numeric(as.character(breast)))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)