有效地计算数据的唯一子集

时间:2018-12-18 14:26:11

标签: r data.table

我有一个比较大的数据集,我不认为它是“大数据”。它大约有3到500万行;由于大小,我正在使用data.table库进行分析。

本质上可以将数据集(名为df,这是一个data.table结构)分解为:

  1. n标识以下字段,即ID_1,ID_2,...,ID_n,其中一些是数字的,其中一些是字符向量。

  2. m个类别变量,以下为C_1,...,C_m,它们都是字符向量,每个值的值很少(一个值二个,另一个值三个,等等...)

    < / li>
  3. 2个测量变量M_1和M_2,均为数字。

数据的子集由ID_1到ID_n标识,具有C_1到C_m的所有值的完整集合,并且值的范围为M_1和M_2。数据子集由126条记录组成。

我需要准确地计算唯一的数据集,并且由于数据的大小,我想知道是否已经存在一种更有效的方法。 (如果其他人更聪明,为什么还要自己动手做呢?)

我已经做了大量的Google工作来得出以下方法。

我所做的是使用ht()库,以便可以将数据框用作哈希值(在后台使用摘要)。

我将ID字段粘贴在一起以创建一个新的单列,以下称为ID,类似于...

ID = "ID1:ID2:...:IDn"

然后,我遍历每个唯一的标识符集,然后仅使用C_1至C_m,M_1和M_2(126行数据)的子集数据帧,对值进行哈希处理/对哈希进行递增。

然后,我要获取该信息并将其放回数据框中。

# Create the hash structure
datasets <- ht()
# Declare the fields which will denote a subset of data
uniqueFields <- c("C_1",..."C_m","M_1","M_2")
# Create the REPETITIONS field in the original data.table structure
df[,REPETITIONS := 0]
# Create the KEY field in the original data.table structure
df[,KEY := ""]

# Use the updateHash function to fill datasets
updateHash <- function(val){
    key <- df[ID==val,uniqueFields,with=FALSE]
    if(isnull(datasets[key])){
        # If this unique set of data doesn't already exist in datasets...
        datasets[key] <- list(val)
    }else{
        # If this unique set of data does already exist in datasets...
        datasets[key] <- append(datasets[key],val)
    }
}

# Loop through the ID fields. I've explored using apply; this vector is around 10-15K long. This version works.
for(id in unique(df$ID)){
    updateHash(id)
}

# Now update the original data.table structure so the analysis can be done. Again, I could use the R apply family, this version works.
for(dataset in ls(datasets)){
    IDS <- unlist(datasets[[dataset]]$val)
    # For this set of information, how many times was it repeated?
    df[ID%in%IDS, REPETITIONS := length(datasets[[dataset]]$val)]
    # For this set, what is a unique identifier?
    df[ID%in%IDS, KEY := dataset]
}

这确实达到了我想要的目的,但是速度却并不快。我现在有能力向关心它的人介绍一些围绕数据集变异性的整洁分析。我不喜欢它是hackey,无论如何,我将清理它并使它变得更好。在此之前,我想做最后的尽职调查,看看是否仅仅是我的Google Fu让我失败了。

0 个答案:

没有答案
相关问题