davidcarslaw · GitHub

Given some simple data:

dat <- data.frame(grp = rep(1:4, each = 2),
                  val = c(NA, 2, 3:8),
                  val2 = c(3, 4, NA, 1, 5:8))

and a simple function:

Mean <- function(x, thresh = 2) {
  res <- mean(x, na.rm = TRUE)
  if (res > thresh) res else NA
}

Now apply to data:

dat %>%
  group_by(grp) %>%
  summarise_each(funs(Mean(., thresh = 2)))
# Source: local data frame [4 x 3]
#   grp  val val2
#1   1   NA  3.5
#2   2 TRUE   NA
#3   3 TRUE  5.5
#4   4 TRUE  7.5

The problem is that the first column becomes boolean instead of numeric. I think this is because the first returned result is NA as it works OK for the second column that also has an NA but it appears further down...

All the best

David

Read the original on github.com ↗