Sometimes you want to create a new variable that is a constant, but you do not know the exact numerical value of the constant. For example, if you want to create a variable that is the mean of another variable, you could do a proc means and then a data step to create the new variable. The code fragment below shows how to output the mean (or whatever statistic that you like) to a data set, and then merge that data set with your original data set. This is not as straightforward as it might seem at first, because the two data sets do not have a common variable on which to do the merge. Another way to think of this is as merging a data file with only one record to a data file with many records.
data test; input studentid class score1 score2; cards; 1 1 34 24 2 1 39 25 3 1 34 26 4 1 38 20 5 1 32 21 1 2 45 36 2 2 43 30 3 2 48 39 4 2 41 37 5 2 40 31 1 3 50 46 2 3 51 49 3 3 57 48 4 3 50 40 5 3 57 46 ; run; proc means data = test mean; var score1 score2; output out = test1 mean=m1 m2; run; data test2; merge test test1; retain mean1 mean2; if _n_ = 1 then do; mean1 = m1; mean2 = m2; end; drop _freq_ _type_ m1 m2; run; proc print data = test2; run;
Obs studentid class score1 score2 mean1 mean2 1 1 1 34 24 43.9333 34.5333 2 2 1 39 25 43.9333 34.5333 3 3 1 34 26 43.9333 34.5333 4 4 1 38 20 43.9333 34.5333 5 5 1 32 21 43.9333 34.5333 6 1 2 45 36 43.9333 34.5333 7 2 2 43 30 43.9333 34.5333 8 3 2 48 39 43.9333 34.5333 9 4 2 41 37 43.9333 34.5333 10 5 2 40 31 43.9333 34.5333 11 1 3 50 46 43.9333 34.5333 12 2 3 51 49 43.9333 34.5333 13 3 3 57 48 43.9333 34.5333 14 4 3 50 40 43.9333 34.5333 15 5 3 57 46 43.9333 34.5333