Calculate the percentage of zeros that I have in a column

后端 未结 4 386
伪装坚强ぢ
伪装坚强ぢ 2021-01-19 17:59

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

相关标签:
4条回答
  • 2021-01-19 18:04
    nrow(df[df$catch.rate == 0,])/nrow(df)
    
    0 讨论(0)
  • 2021-01-19 18:05
    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
    
    0 讨论(0)
  • 2021-01-19 18:06
    sum(df$catch.rate==0)/length(df$catch.rate)
    

    There's probably a more R-ish way, but this is the quickest I could come up with.

    0 讨论(0)
  • 2021-01-19 18:20
    mean(!df$catch.rate)
    

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

    0 讨论(0)
提交回复
热议问题