r - summarizing data based on a pre-set condition and adding a (0,1) flag -
i have following data frame df
following columns:
df <- rep metric 1 1 2 0 3 1 1 b 1 2 b 1 3 b 1 1 c 0 2 c 1 3 c 1
i want summarize data rep such each unique rep
if be
1
both metric
a
, b
add new column beboth
1
otherwise 0
(i.e. if of them zero, beboth
zero).
the output should be:
rep beboth 1 1 2 0 3 1
how may in r? triled use ifelse
statement didn't right!
here's came with
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"), = 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 beboth # (dbl) (chr) (dbl) (dbl) #1 1 1 1 #2 2 0 0 #3 3 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
if care rep , beboth can summarize it:
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
edit: updated answer have @ , b
Comments
Post a Comment