How do I find the length of grouped columns, excluding NAs?
For example, with the following data frame,
Year State var1 var2
TX 2 NA
WA 0 3
CA NA 1
CA 2 NA
CA 2 3
TX NA 4
WA NA NA
WA 3 3
CA NA 0
I want it to return
State var1 var2
TX 1 1
WA 2 2
CA 2 3
Some similar questions have been asked (e.g. R - Get number of values per group without counting NAs) but I'm still struggling to get the output I want.
I've tried several variations on summarise_if
and summarise_all
, but they either throw up errors or don't calculate the right thing.
counts <- df %>%
group_by(State) %>%
summarise_all(funs(length(!is.na(.))))