gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:45:07 25 4
gpt4 key购买 nike

我有以下两个重复实验的数据框。我想根据每个时间戳和 ID 的 score == 0 在两个重复中过滤 df

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

关于r - 在 R 中按分组复制过滤数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59323113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com