vendredi 6 août 2021

Multiple ifelse in R

I have the following data set in R :

gear = c("OTB","OTB",rep("PS",6),"LL","LLD","LTL","LHP","LHM","LL","LLD","LTL","LHP","LHM",
         "LL","LLD","LTL","LHP","LHM","LL","LLD","LTL","LHP","LHM","GNS","GTN","GTR","FPO","NK","SB");gear
fish = c("MUR","SWO","BFT","SWO","ALB","MUR","MUT","SPC",rep("SWO",5),rep("BFT",5),rep("ALB",5),"MUR","MUT","SPC","DRG","KEK","MUR","SWO","BFT","BFT","BFT","SWO")
MED = c("M01","M01",rep("M04",3),rep("M03",3),rep("M06",15),rep("M05",5),rep("M07",3),"M09",rep("M12",2))
d = data.frame(gear,fish,MED);
print(d) 

Where the MED variable is the right result that I have to make in a multiple if else statement.

My difficulty is that has multiple AND OR operators that confuses me in coding.

I have the condition in column fish for PS,LL,LLD,LTL,LHP,LHM.

The rest have the condition only on gear.

my effort is this :

med= ifelse(d$gear == "OTB","MED01",
            ifelse(d$gear=="PS" & d$fish == "BFT" | d$fish == "SWO" | d$fish == "ALB","MED04",
                   ifelse(d$gear=="PS" & d$fish != "BFT" | d$fish != "SWO" | d$fish != "ALB","MED03",
                          ifelse(d$gear=="LL" | d$gear=="LLD" | d$gear=="LTL" | d$gear=="LHP" | d$gear=="LHM" & d$fish=="BFT" | d$fish=="SWO" | d$fish=="ALB","MED06",
                                 ifelse(d$gear=="LL" | d$gear=="LLD" | d$gear=="LTL" | d$gear=="LHP" | d$gear=="LHM" & d$fish!="BFT" | d$fish!="SWO" | d$fish!="ALB","MED05",
                                        ifelse(d$gear== "GNS" & d$gear== "GTN" & d$gear== "GTR","MED07",
                                               ifelse(d$gear=="FPO","MED09",
                                                      "MED12")))))));med
cbind(d,med)

But does not produces the right result comparing to the column MED. Any help?

Aucun commentaire:

Enregistrer un commentaire