我的数据框中有大约 200 列。我希望将数据类型为 char 的列转换为因子,然后转换为级别或整数。
例如,Man 变成 1。
以下代码手动工作,
as.factor(df$colName1)
as.integer(df$colName1)
但是我们如何使用循环对所有列进行检查,然后对其进行转换?
谢谢。
df <- apply(df,2,function(x){
if(is.character(x)){
x <- as.factor(x)
levels(x) <- 1:length(levels(x))
return(x)
}
})
## I believe that this should work
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句