r - 将组合因子列拆分为 r data.table 中的两个因子列的最有效方法是什么?

标签 r data.table stringr

我有一个包含两列的大型 data.table(9 M 行):fcombined 和 value fcombined 是一个因素,但它实际上是两个因素相互作用的结果。 现在的问题是,将一个因子列再次一分为二的最有效方法是什么? 我已经想出了一个可以正常工作的解决方案,但也许我错过了更直接的方法。工作示例是:

library(stringr)
f1=1:20
f2=1:20
g=expand.grid(f1,f2)
combinedfactor=as.factor(paste(g$Var1,g$Var2,sep="_"))
largedata=1:10^6
DT=data.table(fcombined=combinedfactor,value=largedata)


splitfactorcol=function(res,colname,splitby="_",namesofnewcols){#the nr. of cols retained is length(namesofnewcols)
  helptable=data.table(.factid=seq_along(levels(res[[colname]])) ,str_split_fixed(levels(res[[colname]]),splitby,length(namesofnewcols)))
  setnames(helptable,colnames(helptable),c(".factid",namesofnewcols))
  setkey(helptable,.factid)
  res$.factid=unclass(res[[colname]])
  setkey(res,.factid)
  m=merge(res,helptable)
  m$.factid=NULL
  m
}
splitfactorcol(DT,"fcombined",splitby="_",c("f1","f2"))

最佳答案

我认为这可以解决问题,而且速度提高了大约 5 倍。

setkey(DT, fcombined)
DT[DT[, data.table(fcombined = levels(fcombined),
                   do.call(rbind, strsplit(levels(fcombined), "_")))]]

我拆分了级别,然后简单地将结果合并回原始 data.table

顺便说一句,在我的测试中,strsplitstringr 函数快 2 倍(对于此任务)。

关于r - 将组合因子列拆分为 r data.table 中的两个因子列的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115571/

相关文章:

r - 如何在 R 中将因子级别转换为列表

r - 在编写自己的 R 包时,我似乎无法正确导入其他包

r - 在 R 中实现 nextafter 功能

r - 如何在 R 中读取分隔 "::"的 .dat 文件

r - 数据表映射

python - 创建一个基于 Python 中的另一列递增的列

r - 将前后单词连接到与 R 中的条件匹配的单词

r - 在r中将街道地址分为街道编号和街道名称

r - 在 R 中对连续日期进行分组

r - 在带有矢量元素的小标题上使用 dplyr 的问题 [列表列]