根据预设条件汇总数据并添加 (0,1) 标志

summarizing data based on a pre-set condition and adding a (0,1) flag

我有以下数据框 df,其中包含以下列:

df <-   
REP  METRIC  BE 
1     A      1
2     A      0
3     A      1
1     B      1
2     B      1 
3     B      1
1     C      0
2     C      1
3     C      1

我想通过 REP 总结数据,这样对于每个唯一的 REP 如果 BE1 对于 Metric AB 然后添加一个新列 BEBOTH1 否则它是 0 (即如果其中任何一个为零,则 BEBOTH 为零)。

输出应该是:

 REP  BEBOTH
  1     1
  2     0
  3     1  

我如何在 R 中执行此操作?我尝试使用 ifelse 语句,但我没有做对!

这是我想出的

library(dplyr)
df <- data_frame(rep = c(1,2,3,1,2,3,1,2,3),
             metric  = c("A", "A", "A", "B", "B", "B", "C", "C", "C"),
             be      = c(1,0,1,1,1,1,1,1,0))

res <- df %>% 
group_by(rep) %>%
mutate(beboth = ifelse(grep("A|B", metric) && be==0, 0, 1))

res
#Source: local data frame [9 x 4]
#Groups: rep [3]
#
#    rep metric    be beboth
#  (dbl)  (chr) (dbl)  (dbl)
#1     1      A     1      1
#2     2      A     0      0
#3     3      A     1      1
#4     1      B     1      1
#5     2      B     1      0
#6     3      B     1      1
#7     1      C     1      1
#8     2      C     1      0
#9     3      C     0      1

如果你只关心rep和beboth,你可以总结一下:

res.summarized <- df %>% 
  group_by(rep) %>%
  mutate(beboth = ifelse(grep("A|B", metric) && be==0, 0, 1)) %>%
  summarize(first(beboth))

res.summarized
#Source: local data frame [3 x 2]
#
#    rep first(beboth)
#  (dbl)         (dbl)
#1     1             1
#2     2             0
#3     3             1

编辑:我更新了我的答案,让它只查看 A 和 B

使用基础包回答:

evaluate_BEBOTH <- function(x){
    subset_df <- df[x,]

    if (sum(subset_df[,'BE']) == 2)
        return (1)
    else
        return (0)
}

df$BEBOTH <- ave(1:nrow(df),df$REP,FUN = evaluate_BEBOTH)

df
  REP METRIC BE BEBOTH
1   1      A  1      1
2   2      A  0      0
3   3      A  1      1
4   1      B  1      1
5   2      B  1      0
6   3      B  1      1

我们可以使用data.table。将 'data.frame' 转换为 'data.table' (setDT(df)),按 'REP' 分组,我们得到逻辑条件并将其用 + 包裹以强制转换为数字。

library(data.table)
setDT(df)[, .(BEBOTH= +(any((METRIC=="A" & BE==1)) & any(METRIC=="B" & BE==1))) , by = REP]
#   REP BEBOTH
#1:   1      1
#2:   2      0
#3:   3      1

或者使用与dplyr

相同的逻辑
library(dplyr)
df %>%
  group_by(REP) %>% 
  summarise(BEBOTH = +(any(METRIC=="A" & BE==1) & any(METRIC=="B" & BE==1)))
#    REP BEBOTH
#   (int)  (int)
#1     1      1
#2     2      0
#3     3      1