mardi 31 octobre 2017

nested if else statement in R with FIRST from SAS

I would like to replicate the following SAS code in R:

     if first.permno then do;
 LME=me/(1+retx); cumretx=sum(1,retx); me_base=LME;weight_port=.;end;
 else do;
 if month(date)=7 then do;
    weight_port= LME;
    me_base=LME; /* lag ME also at the end of June */
    cumretx=sum(1,retx);
 end;
 else do;
    if LME>0 then weight_port=cumretx*me_base;
    else weight_port=.;
    cumretx=cumretx*sum(1,retx);

My code in R is:

CRSP_merged1 <- within(CRSP_merged1, 
          if(CRSP_merged1$PERMNO != lag(CRSP_merged1$PERMNO)){
            CRSP_merged1$lag_ME <- CRSP_merged1$ME/(1+CRSP_merged1$RET_ADJ)
            CRSP_merged1$cumret <- sum(1, CRSP_merged1$RET_ADJ)
            CRSP_merged1$ME_base <- CRSP_merged1$lag_ME
            CRSP_merged1$weight_port <- 0
          } else if (month(CRSP_merged1$Date) == 7){
            CRSP_merged1$weight_port <- lag_ME
            CRSP_merged1$ME_base <- CRSP_merged1$lag_ME
            CRSP_merged1$cumret <- sum(1, CRSP_merged1$RET_ADJ)
          } else if (CRSP_merged1$lag_ME > 0){
            CRSP_merged1$weight_port <- CRSP_merged1$cumret * CRSP_merged1$ME_base
          } else {
            CRSP_merged1$weight_port <- 0
            CRSP_merged1$cumret <- CRSP_merged1$cumret * sum(1, CRSP_merged1$RET_ADJ)
}
)

I am especially struggling to replicate the FIRST function from SAS. I looked at a number of posts in the forum like http://ift.tt/2h33FQ9 but I wasn`t able to amend this to my case. What I am trying to achieve is: My dataframe "CRSP_merged1" is sorted by date and PERMNO (which is a stock identifier). For every row in the dataframe, if its a new PERMNO go the first if-loop and create the new dataframe variables "lag_ME", "cumret", "ME_base" and "weight_port". If the month of the date is 7 go the second if-loop and adjust the new variables, if ME>0 go the third loop, otherwise go the last loop. Thanks for any help with this!

Aucun commentaire:

Enregistrer un commentaire