Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the percentage of zeros that I have in a column

Tags:

dataframe

r

I have a column of catch rate data in a DF (df$catch.rate) that contains a combination of decimal values and zeros.

I would like to calculate the percentage of zero rows in the whole column to give me an indication of their contribution to the data.

like image 853
user3489562 Avatar asked Dec 06 '22 23:12

user3489562


2 Answers

mean(!df$catch.rate)

will do the trick. You can add the argument na.rm = TRUE if there are NAs.

like image 126
Sven Hohenstein Avatar answered Apr 30 '23 21:04

Sven Hohenstein


sum(df$catch.rate %in% 0 ) / nrow(df)

I suggest using %in% if you have NA values..... e.g.

x <- c(0,NA,1) 
sum(x == 0 ) / length(x)
#[1] NA
like image 23
user1317221_G Avatar answered Apr 30 '23 21:04

user1317221_G