Hi all,
I want to know what is the differences between these two statements: (highlighted in red color)
proc sort data=com;
by dis;
run;
data com;
set com;
by dis;
if first.dis then disn+1; (if first.dis then disn=disn+1)
run;
when I run each program, the value of disn is different. I want to know the difference between disn+1 and disn=disn+1.
Thanks
dsn + 1;
is a sum statement. It implicitly adds:
retain dsn 0;
dsn = dsn + 1;
is an assignment statement. There is no implicit retain.
dsn + 1;
is a sum statement. It implicitly adds:
retain dsn 0;
dsn = dsn + 1;
is an assignment statement. There is no implicit retain.
When you use a statement like this:
if first.dis then disn+1;
Then the variable DISN is created with an implied Retain statement which means the value is carried from record to record in the data step. If there is a variable in the dataset name in a SET statement then that value gets reset each time a record is pulled from the dataset.
So the statement as used will increase a count by 1 for each first level of the variable DIS when the statement executes.
if first.dis then disn=disn+1;
If the variable DISN is not declared with a RETAIN statement and this is the first use then the value of Disn starts as missing. When a missing value has 1 added this way the result is missing. Unless there is a variable Disn in your com set I would expect the result to be missing from the addition. If you do have a Disn variable then the result would be the addition of 1 to that value when not missing.
If you need to sum values when something may be missing use the SUM function. However without a retain such as your example the result of disn = sum(disn,1); would likely be 1 for every record.
To make it the same, add the RETAIN, if desired.
This should make disn and disn2 the exact same.
data com1;
set com;
by dis;
retain disn;
if first.dis then disn=disn+1;
if first.dis then disn2+1;
run;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.