Select ID vectors with certain characteristics in R

2

I have a data frame with four columns of values for each ID and I need to create a new df excluding the IDs whose vectors have more than zero or more than one NA.

I created the DF

library(dplyr)
co_entidade<-c(23, 40, 58, 82, 104, 171,    198, 201, 202,244)
depend<-c(2,3,4,4,4,4,4,2,3,4)
mat13<-c(42,    218,    1397,   0,    393,    283, 1053,  529,    NA, 664)
mat14<-c(44,    222,    1300,   0,    428,    246,    994,    521,    NA, 678)
mat15<-c(40,    215,    1345,   199,    0,    226,    1069,   566,    NA, 598)
mat16<-c(10,    208,    1442,   154,    0,    229,    1033,    NA,    521,552)

df<-data.frame(co_entidade, depend, mat13, mat14, mat15, mat16)
df  

Itriedtoapplyafilterwiththepackagedplyrthatevenremovesthe0andNAs,butthesystemreturnstheidsseparatedbyyear,aspicturebelow

desc_0_NA<-df%>%gather(mat_tipo,mat_valor,mat13:mat16)%>%filter(mat_valor>0,mat_valor!="NA")
desc_0_NA

ButwhatIneedistoremovetheco_entitythathasmorethanavalueof0orNA,inthisexampleIwillhavetoobtainadfwithoutthecodes82,104and202,underlinedinredintheimagebelow.Sincethesevectors(82and104)havemorethanonezeroormoreofanNA(202).

If anyone knows how to do this in R, regardless of the years where zeros or NAs are.

Thank you in advance

    
asked by anonymous 24.05.2017 / 20:05

1 answer

2

First I created a is.0() function in the form of is.na() to test if the cell value is equal to 0

is.0 <- function(x){x == 0}

Then I used the functions of package dplyr

df <- df %>% 
  mutate(S.0 = rowSums(is.0(.), na.rm = T),
         S.NA = rowSums(is.na(.))) %>% 
  filter(S.0 <= 1) %>% 
  filter(S.NA <= 1) %>% 
  select(-contains("S."))
df
    
24.05.2017 / 22:08