提高 R 中 split() 函数的性能? [英] Improving performance of split() function in R?

查看:33
本文介绍了提高 R 中 split() 函数的性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的数据框:

I have a data frame in a very simple form:

    X Y
    ---
    A 1
    A 2
    B 3
    C 1
    C 3

我的最终结果应该是这样的列表:

My end result should be a list like this:

$`A`
[1] 1 2

$`B`
[1] 3

$`C`
[1] 1 3

对于这个操作,我在 R 中使用了 split() 函数:

For this operation I am using the split() function in R:

k <- split(Y, X)

这工作得很好.但是,如果我想将此代码应用于包含 2200 万行(包括 1000 万个 X 组和 387000 个 Y 值的数据框),它变得非常耗时.我尝试使用 RRO 8.0 开放版本来支持 MKL.但是,仍然只使用了一个内核.CPU 有 64 GB 的 RAM,所以这应该不是问题.

This is working just fine. However, if I want to apply this code on a data frame containing 22 million rows including 10 million groups for X and 387000 values for Y it becomes really time consuming. I tried using the RRO 8.0 open version for MKL support. However, still only one Kernel is used. The CPU has 64 GB of RAM so that shouldn't be an issue.

有没有更聪明的方法来计算这个的想法?

Any ideas for a smarter way to compute this?

推荐答案

尝试

 library(data.table)
 DT <- as.data.table(df)
 DT1 <- DT[, list(Y=list(Y)), by=X]
 DT1$Y
 #[[1]]
 #[1] 1 2

 #[[2]]
 #[1] 3

 #[[3]]
 #[1] 1 3

或者使用 dplyr

 library(dplyr)
 df1 <-  df %>% 
             group_by(X) %>%
              do(Y=c(.$Y))

 df1$Y
 #[[1]]
 #[1] 1 2

 #[[2]]
 #[1] 3

 #[[3]]
 #[1] 1 3

数据

 df <- structure(list(X = c("A", "A", "B", "C", "C"), Y = c(1L, 2L, 
 3L, 1L, 3L)), .Names = c("X", "Y"), class = "data.frame", row.names = c(NA, 
 -5L))

这篇关于提高 R 中 split() 函数的性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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