Now I am multiplying the following numbers recursively.
data a;
input a b;
cards;
1 1.1
1 1.1
1 1.1
1 1.1
1 1.1
2 1.2
2 1.2
2 1.2
2 1.2
2 1.2
;
run;I can use RETAIN to do this.
data a;
set a;
by a;
retain c 1;
c=c*b;
put c;
run;The problem is, SAS multiplies all the numbers, while I want to apply RETAIN for each BY—restarting at the sixth here.
16 data a;
17 set a;
18 by a;
19 retain c;
20 if first.a then c=1;
21 c=c*b;
22 put c;
23 run;
1.1
1.21
1.331
1.4641
1.61051
1.2
1.44
1.728
2.0736
2.48832
NOTE: There were 10 observations read from the data set WORK.A.
NOTE: The data set WORK.A has 10 observations and 3 variables.
NOTE: DATA statement used (Total process time):
real time 0.04 seconds
cpu time 0.03 secondsIs there any way to do this? By the way, I know that
if first.a then c=1;works in this case, but I wonder whether RETAIN is directly applicable for each BY more generally—I tried IF FIRST.A THEN RETAIN C 1; here but did not work. Thanks.
Hi @Junyong
Retain is a compile-time statement, and it just tells SAS not to reset the value to missing before each input record is read. It is not necessary to supply a value to supply a value in the retain statement.
So everything works if you assign the value of b to c in the first observation in each by group:
data b;
set a;
by a;
retain c;
if first.a then c = b;
else c = c * b;
run;
Is there any way to do this? By the way, I know that
if first.a then c=1;
works in this case, but I wonder whether RETAIN is directly applicable for each BY more generally—I tried IF FIRST.A THEN RETAIN C 1; here but did not work. Thanks.
Of course won't work because RETAIN is a compile time statement whereas IF THEN is an execution time statement. Are you looking for something fancy?
Or you could mimic a retain to make it seem like as though you declared only once with a DOW loop
data a;
c=1;
do until(last.a);
set a;
by a;
c=c*b;
put c;
end;
run;
Nevertheless, I see no value regardless
Something I fancied to get your results
data a;
set a;
by a;
if first.a then grp=1;
else grp+1;
c=b**grp;
put c;
run;
Hi @Junyong
Retain is a compile-time statement, and it just tells SAS not to reset the value to missing before each input record is read. It is not necessary to supply a value to supply a value in the retain statement.
So everything works if you assign the value of b to c in the first observation in each by group:
data b;
set a;
by a;
retain c;
if first.a then c = b;
else c = c * b;
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
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.
Ready to level-up your skills? Choose your own adventure.