首页 > 解决方案 > 获取具有特定数量重复值的行

问题描述

在 R 中,我有一个大数据框,其中前两列是主 ID(对象)和辅助 ID(对象的元素)。我想创建这个数据帧的一个子集,条件是主 ID 和辅助 ID 必须在前一个数据帧中重复 20 次。我还必须对具有相同结构的其他数据框重复此过程。

现在,我首先计算每对值(主 ID 和辅助 ID)在新数据帧中重复自身的次数,然后使用for循环创建新数据帧,但该过程非常缓慢且效率低下:循环写入从具有 500.000 到 100 万行的数据帧开始,每秒 20 行。

for (i in 1:13){
  x <- fread(dataframe_list[i]) #list which contains the dataframes that have to be analyzed
  x1 <- ddply(x,.(Primary_ID,Secondary_ID), nrow) #creating a dataframe which shows how many times a couple of values repeats itself
  x2 <- subset(x1, x1$V1 == 20) #selecting all couples that are repeated for 20 times
  for (n in 1:length(x2$Primary_ID)){
    x3 <- subset(x, (x$Primary_ID == x2$Primary_ID[n]) & (x$Secondary_ID == x2$Secondary_ID[n]))
    outfiles <- paste0("B:/Results/Code_3_", Band[i], ".csv")
    fwrite(x3, file=outfiles, append = TRUE, sep = ",")
  }
}

例如,如何将前一个数据帧中的所有行作为主要和次要 ID 的值,这些行一次在 x2 数据帧中获得,而不是一次写入一组 20 行?也许在 SQL 中更容易,但我现在必须处理 R。

编辑:

当然。假设我从这样的数据框开始(对于其他具有重复 ID 的行,我将停止到 5 行简短):

      Primary ID  Secondary ID  Variable
    1          1             1    0.5729 
    2          1             2    0.6289
    3          1             3    0.3123
    4          2             1    0.4569
    5          2             2    0.7319

然后用我的代码在一个新的数据框中计算重复的行(阈值为 4 而不是 20,所以我可以给你一个简短的例子):

      Primary ID  Secondary ID     Count
    1          1             1         1
    2          1             2         3
    3          1             3         4
    4          2             1         2
    5          2             2         4

想要的输出应该是这样的数据框:

      Primary ID  Secondary ID  Variable
    1          1             3    0.5920
    2          1             3    0.6289
    3          1             3    0.3123
    4          1             3    0.4569
    5          2             2    0.7319
    6          2             2    0.5729
    7          2             2    0.6289
    8          2             2    0.3123

标签: rdataframestatistics

解决方案


如果有人感兴趣,我设法找到了一种方法。用上面的代码计算这对值重复了多少次后,可以通过这种简单的方式获得我想要的输出:

#Select all the couples that are repeated 20 times
x2 <- subset(x1, x1$V1 == 20)
#Create a dataframe which contains the repeated primary and secondary IDs from x2
x3 <- as.data.frame(cbind(x2$Primary_ID, x2$Secondary_ID)
#Wanted output
dataframe <- inner_join(x, x3)

#Joining, by c("Primary_ID", "Secondary_ID")

推荐阅读