将多个data.table列转换为R中的因子 [英] Converting multiple data.table columns to factors in R

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

问题描述

当尝试将数据表的多个列转换为因子列时,遇到了意外的问题。我已经将它复制如下:

  library(data.table)
tst< - data.table 'a'= c('b','b','c','c'))
class(tst [,a])
tst [,as.factor返回预期结果
tst [,as.factor('a'),with = FALSE] #Returns error



后面的命令返回Math.factor(j)中的错误:abs对因子没有意义。我发现这个尝试获取tst [,lapply(cols,as.factor),with = FALSE]其中cols是我试图转换因子的行的集合。

解决方案

我找到一个解决方案:

  library(data.table)
tst< - data.table('a'= c('b','b','c' c'))
class(tst [,a])
cols < - 'a'
tst [,(cols):= lapply(.SD,asfactor)。 SDcols = cols]

然而,前面提到的行为似乎有错误。


I ran into an unexpected problem when trying to convert multiple columns of a data table into factor columns. I've reproduced it as follows:

library(data.table)
tst <- data.table('a' = c('b','b','c','c'))
class(tst[,a])
tst[,as.factor(a)]  #Returns expected result
tst[,as.factor('a'),with=FALSE] #Returns error

The latter command returns 'Error in Math.factor(j) : abs not meaningful for factors'. I found this when attempting to get tst[,lapply(cols, as.factor),with=FALSE] where cols was a collection of rows I was attempting to convert to factors. Is there any solution or workaround for this?

解决方案

I found one solution:

library(data.table)
tst <- data.table('a' = c('b','b','c','c'))
class(tst[,a])
cols <- 'a'
tst[,(cols):=lapply(.SD, as.factor),.SDcols=cols]

Still, the earlier-mentioned behavior seems buggy.

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

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