简体   繁体   中英

subset all rows except those with a specific condition with group_by for varying number of variables in r

I wish to filter this df

Sample <- c(1:24)
Group <- c("A","A","A","A","A","A","A","A","A","A","A","A", "B","B","B","B","B","B","B","B","B","B","B","B")
T1 <- c(74.4, 74.7, 74.1, 72.2, 72.8, 72.9, 70.8, 71.2, 70.5, 72.4, 72.7, 72.1, 71.2, 71.8, 71.9, 70.8, 70.2, 70.5, 72.2, 72.7, 72.1, 70.8, 71.0, 70.7)
S1 <- c("sample", "sample", "sample", "std", "std","std","std","std", "std", "sample", "sample", "sample","sample", "sample", "sample", "std", "std","std", "std", "std", "sample", "sample", "sample", "sample")
df <- data.frame(Sample, Group, T1, S1)

keeping all rows, except the ones where S1=="std" & Group == "A" & T1 %!+-1% median(T1[S1 == "std"]) for each Group to get this output

   Sample Group   T1     S1
1       1     A 74.4 sample
2       2     A 74.7 sample
3       3     A 74.1 sample
4       4     A 72.2    std
7       7     A 70.8    std
8       8     A 71.2    std
10     10     A 72.4 sample
11     11     A 72.7 sample
12     12     A 72.1 sample
13     13     B 71.2 sample
14     14     B 71.8 sample
15     15     B 71.9 sample
16     16     B 70.8    std
17     17     B 70.2    std
18     18     B 70.5    std
21     21     B 72.1 sample
22     22     B 70.8 sample
23     23     B 71.0 sample
24     24     B 70.7 sample
> 

I got help with this nice code

df %>% group_by(Group) %>% filter(T1 %+-1% median(T1[S1 == "std"]))

which filters all rows (not only the S1 == "std" ) but I can't work around it to implement the subset function so that I drop the rows with these conditions.

I still do it like this - which as far as I understand is not the right way, and also it doesn't allow me to do it for a varying number of Groups (if more than 2)

for(Var in unique(df$Group)) {
    assign(paste("T1_", Var, sep = ""), median(filter(df, Group == Var, S1 == "std")$T1))
  }
`%+-1%` <- function(T1, T1_A) (T1 >= T1_A-1) & (T1 <= T1_A+1)
df  %>% subset(!(df$S1=="std" & df$Group == "A" & df$T1 %!+-1% T1_A | 
                 df$S1=="std" & df$Group == "B" & df$T1 %!+-1% T1_B))

This will remove rows in each Group where S1=="std" and Group == "A" and T1 value is between +- 1% of median of T1 where S1 == "std" .

library(dplyr)

df %>%
  group_by(Group) %>%
  filter({
  val <- median(T1[S1 == "std"])     
  !(S1=="std" & T1 %!+-1% val)
  }) %>% 
  ungroup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM