Hi I am doing Programming 2 lesson 2 on trying to find maximum traffic count using RETAIN statement, the example code is as follow:
data cuyahoga_maxtraffic; set pg2.np_monthlyTraffic; where ParkName = 'Cuyahoga Valley NP'; retain TrafficMax 0 MonthMax LocationMax; if Count>TrafficMax then do; TrafficMax=Count; MonthMax=Month; LocationMax=Location; end; format Count TrafficMax comma15.; keep Location Month Count TrafficMax MonthMax LocationMax; run;
I am trying to understand why retain TrafficMax 0? Wouldn't that set the TrafficMax to 0 every row iteration?
for example if row 1 count is 5 and row 2 count is 4 then
TrafficMax is 0 after retain TrafficMax 0
then it is set to 5 after iteration of row 1, then TrafficMax is set back as 0 at the beginning of iteration of row 2, and TrafficMax is set to 4 after iteration of row 2?
Or am I misunderstanding the SAS compiling process, only the if/then statement is looped for each row?
Also adding the 0 in the RETAIN statement does not seem to affect TrafficMax or MonthMax but LocationMax becomes empty. Why is that?
By adding the zero in the RETAIN statement, you define the variable as numeric, so it can't hold the character values of location.
Without the zero, the type of the variable is set later during compilation when the assignment statement is encountered.
PS read the log (Maxim 2). You'll find NOTEs about invalid numeric data.
RETAIN is a declarative statement, not an executable one.
The value is used once during data step compilation to initialize the variable.
Build your skills. Make connections. Enjoy creative freedom. Maybe change the world. Registration is now open through August 30th. Visit the SAS Hackathon homepage.
Register today!Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.