I forgot to cc to rhelp. Petr
Hi Dunno how to do it by dplyr I would use ave df$MinValue <- ave(df$Value, paste(df$Class, df$Department), FUN = function(x) min(x[x>0])) Cheers Petr > > -----Original Message----- > > From: R-help <r-help-boun...@r-project.org> On Behalf Of Elahe chalabi > via > > R-help > > Sent: Tuesday, May 11, 2021 1:12 PM > > To: R-help Mailing List <r-help@r-project.org> > > Subject: [R] Group by and duplicate a value/dplyr > > > > Hi all, > > > > I have the following data frame > > > > > > dput(df) > > 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, 1200L, > > 0L, > > 0L, > > 400L, 400L, 200L, 800L, 1200L, 1200L)), class = "data.frame", row.names = > > c(NA, > > -16L)) > > > > > > I would like to group by "Department" and "Class" and repeat the minimum > > value of "Valule" excluding zeros or get the second minimum value. The > > desired output is: > > > > > > dput(df) > > 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, 1200L, > > 0L, > > 0L, > > 400L, 400L, 200L, 800L, 1200L, 1200L), MinValue = c(100L, 100L, 100L, > > 100L, > > 300L, 300L, 300L, 300L, 400L, 400L, 400L, 400L, 200L, 200L, 200L, 200L)), > > class = > > "data.frame", row.names = c(NA, -16L)) > > > > > > how should I change the following dplyr to give me the desired output? > > > > > > df <- > > df %>% > > group_by(Department,Class) %>% > > mutate(MinValue=min(Value) ) > > > > > > Thanks for any help. > > Elahe > > > > ______________________________________________ > > R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see > > https://stat.ethz.ch/mailman/listinfo/r-help > > PLEASE do read the posting guide http://www.R-project.org/posting- > > guide.html > > and provide commented, minimal, self-contained, reproducible code.
______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.