I'd like to replicate and modify specific rows in the table.
before:
xyz_id | letter | Col_1 | ...|
1 | Z | V1 | ... |
2 | Z | V2 | ... |
3 | Z | V3 | ... |after:
xyz_id | letter | Col_1 | ...|
1 | A | V1.1 | ... |
1 | B | V1.2 | ... |
1 | C | V1.3 | ... |
2 | A | V2.1 | ... |
2 | B | V2.2 | ... |
2 | C | V2.3 | ... |
3 | A | V3.1 | ... |
3 | B | V3.2 | ... |
3 | C | V3.3 | ... |I've prepared the following code:
data test2;
set test;
array letters {3} $3 _temporary_ ('A', 'B', 'C');
array weights {3} _temporary_ (1,2,3);
/* if xyz_id = '1' */
/* then array weights {3} _temporary_ (1,2,3);*/
/* else if xyz_id = '2'*/
/* then array weights {3} _temporary_ (8,7,6);*/
/* else array weights {3} _temporary_ (1,1,1)*/
do i = 1 to 8;
letter = letters(i);
Col_A = Col_A * weights(i);
output;
end;
drop i;
run;Now, I'm trying to make weights depend of the letter column (commented code) - but without any success. I also tried:
array weights_1 {3} _temporary_ (1,2,3);
if xyz_id = '1'
then weights = weights_1;but it didn't work as well.
Any suggestions?
An array is a static object defined once and created during the data step compilation phase. You cannot create it conditionally (unless you generate the code conditionally with macro language).
You can create a large array with all weights, and then set the index conditionally depending on a variable value.
If the weight depends on the ID then why not just put them into another dataset instead of storing the weights in the code?
data have;
input xyz_id letter $ Col_1 col_2;
cards;
1 Z 2 1
2 Z 3 2
3 Z 4 3
;
data weights;
input xyz_id weight1-weight3 ;
cards;
1 1 2 3
2 8 7 6
3 1 1 1
;
data want;
merge have weights ;
by xyz_id;
array weights weight1-weight3 ;
array letters [3] $3 _temporary_ ('A' 'B' 'C');
array old col_1-col_2;
array new new_1-new_2;
do i=1 to dim(letters);
letter=letters[i];
do j=1 to dim(old);
new[j] = old[j] * weights[i];
end;
output;
end;
run;
proc print;
run;
PS It is just as easy to type the data step to create the data as it is to type those tables with the |'s in them. And if you use the Insert SAS Code icon so you get a fixed font it is just as easy to read. The |'s just limit the amount of information you can put on a line.
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!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.