str_rst
str_rst

Reputation: 175

find the count of values having zero in rows in dataframe

i am trying to calculate the count of zero in rows and then subtract it from 5

for eg in excel =3-COUNTIF(SM1:SM3,0)

any solution for this

df <- data.frame("T_1_1"= c(68,NA,0,105,NA,0,135,NA,24),
                 "T_1_2"=c(26,NA,0,73,NA,97,46,NA,0),
                 "T_1_3"=c(93,32,NA,103,NA,0,147,NA,139),
                 "S_2_1"=c(69,67,94,0,NA,136,NA,92,73),
                 "S_2_2"=c(87,67,NA,120,NA,122,0,NA,79),
                 "S_2_3"= c(150,0,NA,121,NA,78,109,NA,0),
                 "T_1_0"= c(79,0,0,NA,98,NA,15,NA,2)
                 
                 
)



df <- df %>% mutate(ltc = (5-rowSums(select(., matches('T_1[1-9]')) == 0,na.rm = TRUE)))

Upvotes: 0

Views: 142

Answers (2)

ThomasIsCoding
ThomasIsCoding

Reputation: 102710

Here is a base R option using rowSums

df$ltc = 5- rowSums(df == 0, na.rm = TRUE)

Upvotes: 0

tonybot
tonybot

Reputation: 655

I believe you forgot an underscore in matches().

df %>%
  mutate(ltc = 5 - rowSums(select(., matches('T_1_[1-9]')) == 0, na.rm = T))

Upvotes: 1

Related Questions