Conditional change or change of all variables in a group

I may have a very simple question about changing a variable clasin mine dfbased on if certain conditions are met. If these conditions are not met, do not change anything.

V <- seq(10,50,10)
gr = rep(seq(1,2),each=5)
clas=c("Normal","Abnormal","Fair","Fair","Normal","Fair","Normal","Normal","Abnormal","Fair")

df <- data.frame(V,gr,clas)

   #      V gr     clas
   #  1  10  1   Normal
   #  2  20  1 Abnormal
   #  3  30  1     Fair
   #  4  40  1     Fair
   #  5  50  1   Normal
   #  6  10  2     Fair
   #  7  20  2   Normal
   #  8  30  2   Normal
   #  9  40  2 Abnormal
   #  10 50  2     Fair

I want to set a column clasfor all values Normal, if shown Normal, when V=20and V=30in each group. If this condition is not met, you do not need to change this group.

Expected Result

df_modif
   #      V  gr    clas
   #  1  10  1   Normal
   #  2  20  1 Abnormal
   #  3  30  1     Fair
   #  4  40  1     Fair
   #  5  50  1   Normal
   #  6  10  2   Normal
   #  7  20  2   Normal
   #  8  30  2   Normal
   #  9  40  2   Normal
   #  10 50  2   Normal
+4
source share
2 answers

Based on OP description

library(dplyr)
df %>%
    group_by(gr) %>% 
    mutate(clas = as.character(clas),
           clas = if(any(clas =="Normal" & V ==20) & 
                     any(clas=="Normal" & V==30)) "Normal"
                 else clas)
#       V    gr     clas
#   (dbl) (int)    (chr)
#1     10     1   Normal
#2     20     1 Abnormal
#3     30     1     Fair
#4     40     1     Fair
#5     50     1   Normal
#6     10     2   Normal
#7     20     2   Normal
#8     30     2   Normal
#9     40     2   Normal
#10    50     2   Normal

The same can be implemented in data.table

library(data.table)
setDT(df)[df[,  .I[any(clas == "Normal" & V == 20) &
     any(clas == "Normal" & V ==30)], gr]$V1, clas := factor("Normal")]
+5
source

Select the value you want to change and then overwrite them

df$clas[df$V %in% c(20, 30)] <- "Normal"
+1

All Articles