在R中按分组复制过滤数据帧

时间:2019-12-13 12:59:20

标签: r dplyr

我有一个具有两个重复的实验的以下数据框。我想根据df在每个时间戳和ID的两个副本中过滤score == 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方式来提高效率吗?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

使用data.table

的方法
library(data.table)
setDT(df)[, .SD[all(score == 0)], by = ID]