【问题标题】:Take rows with a specific number of repeated values获取具有特定数量重复值的行
【发布时间】:2019-09-04 01:18:11
【问题描述】:

在 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 和辅助 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

【问题讨论】:

  • 你能准备一个具有预期输出的可重现的小例子吗?

标签: r dataframe statistics


【解决方案1】:

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

#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")

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多