Search code examples
rcountpipemagrittr

Count the number of non-zero elements of each column- Piping Friendly


I am a behavioral ecologist using R. I am trying to count the non-zero elements across several columns. Normally when I do this I have successfully employed colSums with the !=0 operator, as has been suggested in many posts here and elsewhere i.e.(Count the number of non-zero elements of each column).

However in this particular case I would really prefer to using piping - as this is simply one step of building out a much larger data frame- and I cannot seem to get colSums with the !=0 to play nicely with the piping. Is there anyway to get this to work or is there a more elegant alternative to counting non-zero values across columns living in the tidy-verse somewhere?

I have put some example code below to demonstrate. Thanks very much!

'''

#make example dataframe
example<- as.data.frame(matrix(sample(c(0,0,0,100),size=70,replace=T),ncol=7))
example<-cbind(Indentifier1="character a",Indentifier2="character b", example)
example


#works great but isn't piping friendly:
colSums(example[-c(1:2)] !=0)  

#Runs but because it lacks the !=0 operator it gives sums not counts of non-zero elements, can't figure out how to employ !=0:
example %>% select(-c(1:2)) %>% colSums() 


#gives me counts of all values, not sure how to call just non-zero values:
example %>% summarise(across(where(is.numeric), length))
 

'''


Solution

  • example %>% summarise(across(where(is.numeric), ~sum(. != 0)))