1. What does the retain statement do here for this code?
It prevents FirstSnow from being reset to missing at the start of the next iteration. So the value is "retained" from iteration to iteration of the data step only changing when a new value is assigned.
2. Why is an If-Then-Do statement necessary here? Why do those assignment statements have to go under the last.Code=1 part?
It is actually NOT needed, only the OUTPUT statement needs to be executed conditionally. Try replacing the IF/THEN/DO/END block with these statement instead.
LastSnow=Date;
WinterLengthWeeks=intck('week', FirstSnow, LastSnow, 'c');
ProjectedFirstSnow=intnx('year', FirstSnow, 1, 'same');
if last.Code then output;
But the IF/THEN/DO block makes the logic clearer to humans and a small amount faster since the assignments statements execute only once per value of CODE.
3. I introduced all the missing parts from the answer code into my code one by one. As soon as I included "output;", the table went from about 140+ rows to only 4. I don't understand how output did this here.
The OUTPUT statement tells the data step to write an observation to the output dataset(s). If your step does NOT have an explicit OUTPUT statement then SAS will imply one that will execute every iteration that reaches the end of the step.
With an OUTPUT statement that executes only once per value of CODE then only one observation per value of CODE will be written out.
Without an explicit OUTPUT statement in that code then every observation read in that reaches the end of the data step is written out. This means you do not even need an OUTPUT statement. Instead you can use a subsetting IF so that only the iterations where you want an observation written makes it to the end of the data step.
if last.Code ;
LastSnow=Date;
WinterLengthWeeks=intck('week', FirstSnow, LastSnow, 'c');
ProjectedFirstSnow=intnx('year', FirstSnow, 1, 'same');
Note that the IF conditions do not need to contain the =1 part you added in your post. The FIRST. and LAST. flags are assigned values of either 1 or 0 . SAS treats any number that is not zero or missing as TRUE. So the code reads more smoothly without the equality test. "if last code" versus "if last code flag's value is one".
... View more