dimanche 29 novembre 2020

filter on a value in a column and remove rows that dont meet condition

I'm relatively new in R. I have this problem. I have data of dogs example of useful part of data (columns age_month and rasnaam (breed) are used)

I have to look for all the breeds if they are small, medium, large etc. And if they are a small breed then all the rows where age_month is lower than 9 have to be removed, if they are a medium sized breed rows where age_month is lower than 13 have to be removed, (large, age_month < 24). I've tried some things but it won't work. I've added all dogs to a list (also tried it with vector) like this: (only for small dogs here)

small_dogs <- list("Affenpinscher", "Bichon frisé", "Bolognezer", "Chihuahua",
            "Dandie Dinmont Terrier", "Dwergkeeshond", "Japanse Spaniel",
            "Griffon belge", "Griffon bruxellois", "Kleine Keeshond", 
            "Lhasa Apso", "Maltezer", "Mopshond", "Pekingees", "Petit Brabançon",
            "Shih Tzu", "Tibetaanse Spaniel", "Volpino Italiano", "Yorkshire Terrier")

I tried this:

for (i in 1:nrow(brachquest2)){
     ifelse((brachquest2$rasnaam %in% small_dogs), (brachquest2 <- brachquest2[!(brachquest2$age_month < 9), ]), 
     ifelse((brachquest2$rasnaam %in% medium_dogs)), (brachquest2 <- brachquest2[!(brachquest2$age_month < 13), ]), 
     (brachquest2 <- brachquest2[!(brachquest2$age_month < 24), ]))
            }

But then I get an unused arguments error. Then I tried to use case_when(), but I'm not familiar with this function, so maybe I'm using it awfully wrong:

brachquest2 <- case_when(
  brachquest2$rasnaam %in% small_dogs ~ brachquest2[!(brachquest2$age_month < 11), ],
  brachquest2$rasnaam %in% medium_dogs ~ brachquest2[!(brachquest2$age_month < 13), ]
  )

Then I get an error: must be length 66 or one, not 18.

(the number of rows is 66)

I hope I explained it okay. Does someone have some useful tips for me? Or maybe it could be much simpler, every help is appreciated!! Thanks in advance

Aucun commentaire:

Enregistrer un commentaire