mercredi 25 avril 2018

Faster function than an ifelse() in r

I have 3 columns Flag, Score, Stage.

Flag will have values 1 or 0, Score will be any values above 0. We need to calculate stage values.

so our data (stagedata) will look like this:

              Flag Score Stage
               1    35
               1    0
               0    12
               ....

IF Flag == 1 and score >= 30, the we calculate stage as 2,

and if Flag ==0 or Flag == 1 and score < 30, stage = 1.

Any other case stage will be calculated as 0 (ie, due to some error in input or if score or flag is missing).

        stagedata$Stage <- ifelse(stagedata$Flag==1,ifelse((stagedata$Score>=30),2,1),ifelse(stagedata$Flag==0,1,0))
        stagedata$Stage[is.na(stagedata$Stage)] <-0

IS there a more efficient way to do this using any other function like apply? The data that we are dealing with are of the order of ten thounsands

Aucun commentaire:

Enregistrer un commentaire