[R] Group by and add a constant value based on a condition dply

Elahe chalabi ch@|@b|@e|@he @end|ng |rom y@hoo@de
Wed May 26 17:52:26 CEST 2021


Hi everyone,

I have the following dataframe: 



      structure(list(Department = c("A", "A", "A", "A", "A", "A", "A", 
     "A", "B", "B", "B", "B", "B", "B", "B", "B"), Class = c(1L, 1L, 
    1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), Value = c(0L, 
    100L, 800L, 800L, 0L, 300L, 1200L, 0L, 0L, 0L, 400L, 400L, 200L, 
    800L, 1200L, 0L), Date = c("1.01.2020", "2.01.2020", "3.01.2020", 
    "4.01.2020", "1.01.2020", "2.01.2020", "3.01.2020", "4.01.2020", 
    "1.01.2020", "2.01.2020", "3.01.2020", "4.01.2020", "1.01.2020", 
    "2.01.2020", "3.01.2020", "4.01.2020")), class = "data.frame", row.names = c(NA, 
     -16L))

 using dplyr I need to group by "Depatment" and "Class" and then for all the dates that are "4.01.2020"  and have the "Value" greater than zero  add 5 to the "Value", meaning the desired dataframe will be (NewValue column) : 



   structure(list(Department = c("A", "A", "A", "A", "A", "A", "A", 
 "A", "B", "B", "B", "B", "B", "B", "B", "B"), Class = c(1L, 1L, 
 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L), Value = c(0L, 
 100L, 800L, 800L, 0L, 300L, 1200L, 0L, 0L, 0L, 400L, 400L, 200L, 
 800L, 1200L, 0L), Date = c("1.01.2020", "2.01.2020", "3.01.2020", 
 "4.01.2020", "1.01.2020", "2.01.2020", "3.01.2020", "4.01.2020", 
 "1.01.2020", "2.01.2020", "3.01.2020", "4.01.2020", "1.01.2020", 
 "2.01.2020", "3.01.2020", "4.01.2020"), NewValue = c(0L, 100L, 
 800L, 805L, 0L, 300L, 1200L, 0L, 0L, 0L, 400L, 405L, 200L, 800L, 
 1200L, 0L)), class = "data.frame", row.names = c(NA, -16L))

   
Thanks a lot for any help!
Elahe



More information about the R-help mailing list