mardi 13 février 2018

How to get do loop in SAS to work with date values?

I have a data set containing 4 years data (2014-2017). I want to give every observation a period-variable containing E, E/F or F from an if-criteria.

I got it to work by repeating my code for every year in a data step: data new; set old;

format period $10.;

if year=2014 then do;
    if start<'01feb2014'd and end<='01mar2014'd then period='E'; 
    else if start<'01feb2014'd and end>'01mar2014'd then period='E/F'; 
    else if start>='01feb2014'd then period='F';
end;
if year=2015 then do;
    if start<'01feb2015'd and end<='01mar2015'd then period='E'; 
    else if start<'01feb2015'd and end>'01mar2015'd then period='E/F'; 
    else if start>='01feb2015'd then period='F';
end;

if year=2016 then do;
    if start<'01feb2016'd and end<='01mar2016'd then period='E'; 
    else if start<'01feb2016'd and end>'01mar2016'd then period='E/F'; 
    else if start>='01feb2016'd then period='F';
end;
if year=2017 then do;
    if start<'01feb2017'd and end<='01mar2017'd then period='E'; 
    else if start<'01feb2017'd and end>'01mar2017'd then period='E/F'; 
    else if start>='01feb2017'd then period='F';
end;

run;

But I want to do the code smarter, by using af do loop. I tried this: data new; set old;

format period $10.;

do i=0 to 3;
    if year=(2014+i) then do;

        if start<'01feb(2014+i)'d and end<='01mar(2014+i)'d then period='E'; 
        else if start<'01feb(2014+i)'d and end>'01mar(2014+i)'d then period='E/F'; 
        else if start>='01feb(2014+i)'d then period='F';
    end;

end;

run;

But that doesn't give the right results for the years 2015-2017.

I also tried this:

data new; set old;

format period $10.;

do i=2014 to 2017;
    if year=(i) then do;

        if start<'01feb(i)'d and end<='01mar(i)'d then period='E'; 
        else if start<'01feb(i)'d and end>'01mar(i)'d then period='E/F'; 
        else if start>='01feb(i)'d then period='F';
    end;

end;

run;

But the code can't even run?

What an I missing??

Kind regards.

Aucun commentaire:

Enregistrer un commentaire