I had some very helpful assistance with another of my functions - so here is another
I use min/max a lot with summarise. Often with na.rm = TRUE
Sometimes some of the groups when using group_by have no non-NA values and you get warnings because max/min return +/- Inf if all NA
Questions:
- Is there an off-the-shelf way of eliminating the warnings with blanket suppressWarnings?
- I end up having to test for class == POSIXct.Date and Date because using "as" does not work for those 2 classes. Is there a slicker way of casting the return value to the class of the input x?
MaxNA = function(x,na.rm = TRUE) {
if (na.rm) {
x<-x[!is.na(x)]
}
if (length(x)>0) max(x, na.rm = na.rm) else {
if(is.POSIXct(x)) {
as.POSIXct.Date(NA)
} else if (is.Date(x)){
as.Date(NA)
} else {
as(NA, class(x))
}
}
}
TodayDate = Sys.Date()
Sampledf = tibble(cat = c(1,1,1,2,2,2), date = c(rep(TodayDate,3),rep(as.Date(NA),3)))
#> Error in tibble(cat = c(1, 1, 1, 2, 2, 2), date = c(rep(TodayDate, 3), : could not find function "tibble"
summary = Sampledf %>%
group_by(cat) %>%
summarise(maxdate = MaxNA(date))
#> Error in Sampledf %>% group_by(cat) %>% summarise(maxdate = MaxNA(date)): could not find function "%>%"
print(summary)
#> function (object, ...)
#> UseMethod("summary")
#> <bytecode: 0x0000014dc35edce8>
#> <environment: namespace:base>
Created on 2023-02-24 with reprex v2.0.2