jeudi 30 novembre 2017

R if else statement using plyr or dplyr for multiple conditions

Here is a dataset:

> mydat
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.2
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.2 

I am trying to code; for each species and each section where obs==b2, if doy of b2 > doy of b3, then ranking=="2.4". If doy of b2 < doy of b3, then ranking=="2.2" (remains the same), so I get this result:

> mydat2
species section obs doy ranking
   A      A1  b1 123     2.1
   A      A2  b2 135     2.2
   A      A3  b3 147     2.3
   B      A1  b2 124     2.2
   B      A2  b3 132     2.3
   B      A3  b2 145     2.4
   C      A1  b1 120     2.1
   C      A2  b3 133     2.3
   C      A3  b2 137     2.4 

I used the package plyr to avoid loops because I find loops difficult to understand. I know a lot of people use dplyr instead of plyr nowadays, so I'd by glad for an answer using either plyr or dplyr. Here is my clumsy try:

require (plyr)
mydat2 <- ddply(.data=mydat[mydat$obs == "b2",],
            .variables=c("species", "section"),
            function(x){
              return(data.frame(ifelse(x$doy>x$doy[x$obs=="b3"]), x$ranking=="2.4", x$ranking=="2.2"))})

I get "arguments imply differing number of rows: 0, 1" as error message, I'm not sure how to code this properly. Thank you for your help.

Aucun commentaire:

Enregistrer un commentaire