首页 > 解决方案 > 通过 R 中的分组复制过滤数据帧

问题描述

我有以下两个重复实验的数据框。我想df根据每个时间戳和 IDscore == 0 的两个复制进行过滤。

df <- data.frame(timestamp = c(1, 1, 1, 1, 2, 2, 2, 2),
             ID = c(57, 57, 55, 55, 57, 57, 55, 55),
             replicate= c(1, 2, 1, 2, 1, 2, 1, 2),
             score = c(0, 1, 0, 0, 0, 1, 0, 0))

例如,所需的输出将是:

target <- data.frame(timestamp = c(1, 1, 2, 2), 
                 ID = c(55, 55, 55, 55), 
                 replicate = c(1, 2, 1, 2),
                 score = c(0, 0, 0, 0))

我想出了一个双循环的解决方案,这是不优雅的,而且很可能是低效的:

tsvec <- df$timestamp %>% unique
idvec <- df$ID %>% unique
df_out <- c()

for(i in seq_along(tsvec)){ # loop along timestamps
  innerdat <- df %>% filter(timestamp == tsvec[i])
  for(j in seq_along(idvec)){ # loop along IDs
    innerdat2 <- innerdat %>% filter(ID == idvec[j])
    if(sum(innerdat2$score) == 0){
        df_out <- rbind(df_out, innerdat2)
    } else {
        NULL
    }
  }
}

有没有人有dplyr办法提高效率?

标签: rdplyr

解决方案


library(dplyr)
df %>% group_by(ID) %>% filter(all(score==0))

# A tibble: 4 x 4
# Groups:   ID [1]
  timestamp    ID replicate score
      <dbl> <dbl>     <dbl> <dbl>
1         1    55         1     0
2         1    55         2     0
3         2    55         1     0
4         2    55         2     0

推荐阅读