For example, I have this data frame (df):
Color X1 X2 X3 X4
Red 1 1 0 2
Blue 0 NA 4 1
Red 3 4 3 1
Green 2 2 1 0
I would like to create a function that counts up the number of non-NA
s in "X2" by group (i.e. by "color"). I would like the output of this function in a new data frame named newdf. This is what I would like for output:
Color X2
Red 2
Blue NA
Green 1
So far, I have this code:
Question <- function(Color){
Result <-
rowsum((df[c("X2")] > 0) + 0, df[["X2"]], na.rm = TRUE)
rowSums(Result)[[Color]]
}
Question("Red")
The output this function gives is just Question("Red")= 2
and I would like to instead get my results of all the colors in a new data frame (newdf). Can anyone help with this? Thanks!
tapply(ifelse(is.na(df$X2), NA, 1), df$Color, FUN=sum)
– Molinirowsum:
rowsum(as.numeric(!is.na(dt$X2)), dt$Color)
– Josi