r - 通过 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
办法提高效率?
解决方案
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
推荐阅读
- java - Spring RestTemplate 忽略 package-info.java
- ionic-framework - 在 Ionic 中调整 base64 编码图像的大小
- reactjs - 在创建新的小部件-Reactjs,Redux 时,在调度之间检测到状态突变
- python - 从文本文件中排除行(Python)
- lua - Lua 查找字符串中可能有空格的字符串
- nosql - 对沙发数据库中的复杂键进行排序
- android - 如何从 Android 应用更新自定义日历上的多个客人
- c - 使用 afl-gcc 编译 - 未检测到检测
- r - 遍历列表以通过其名称获取值
- java - 为什么这个正则表达式需要很长时间才能执行?