R -apply- 将许多列从数字转换为因子 [英] R -apply- convert many columns from numeric to factor
本文介绍了R -apply- 将许多列从数字转换为因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将许多数字列转换为因子类型.示例表:
I need to convert many columns that are numeric to factor type. An example table:
df <- data.frame(A=1:10, B=2:11, C=3:12)
我试过申请:
cols<-c('A', 'B')
df[,cols]<-apply(df[,cols], 2, function(x){ as.factor(x)});
但结果是一个字符类.
> class(df$A)
[1] "character"
如果不为每一列做 as.factor,我怎么能做到这一点?
How can I do this without doing as.factor for each column?
推荐答案
尝试
df[,cols] <- lapply(df[,cols],as.factor)
问题在于 apply()
试图将结果绑定到一个矩阵中,这导致将列强制为字符:
The problem is that apply()
tries to bind the results into a matrix, which results in coercing the columns to character:
class(apply(df[,cols], 2, as.factor)) ## matrix
class(as.factor(df[,1])) ## factor
相反,lapply()
对列表的元素进行操作.
In contrast, lapply()
operates on elements of lists.
这篇关于R -apply- 将许多列从数字转换为因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文