R - 将许多列从数字转换为因子 [英] R -apply- convert many columns from numeric to factor

查看:2140
本文介绍了R - 将许多列从数字转换为因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将许多列数字转换为因子类型。
示例表:

  df < -  data.frame(A = 1:10,B = 11,C = 3:12)

我尝试了apply:

  cols< -c('A','B')
df [,cols]< -apply(df [,cols],2 ,function(x){as.factor(x)});

但结果是一个字符类。

 > class(df $ A)
[1]character

$ p

<$ p

$ p> df [,cols]< - lapply(df [,cols],as.factor)

问题是 apply()试图将结果绑定到一个矩阵中,这导致将列强制为字符:

  class(apply(df [,cols],2,as.factor))## matrix 
class(as.factor df [,1]))##因子

相反, lapply )操作列表的元素。


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)

I tried with apply:

cols<-c('A', 'B')
df[,cols]<-apply(df[,cols], 2, function(x){ as.factor(x)});

But the result is a character class.

> class(df$A)
[1] "character"

How can I do this without doing as.factor for each column?

解决方案

Try

df[,cols] <- lapply(df[,cols],as.factor)

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

In contrast, lapply() operates on elements of lists.

这篇关于R - 将许多列从数字转换为因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆