Mean excluding zero and na for all columns with dplyr
If you don't want 0s it's probably that you consider them as NAs, so let's be explicit about it, then summarize numeric columns with na.rm = TRUE
:
library(dplyr)
df[df==0] <- NA
summarize_if(df, is.numeric, mean, na.rm = TRUE)
# n b
# 1 4 4
As a one liner:
summarize_if(`[<-`(df, df==0, value= NA), is.numeric, mean, na.rm = TRUE)
and in base R
(result as a named numeric vector)
sapply(`[<-`(df, df==0, value= NA)[sapply(df, is.numeric)], mean, na.rm=TRUE)
Cf elegant David Answer :
df %>% summarise_each(funs(mean(.[!is.na(.) & . != 0])), -s)
Or
df %>% summarise_each(funs(mean(.[. != 0], na.rm = TRUE)), -s)