2
votes

I want to create a variable want which is a randomly generated number following uniform distribution for dataset data. I want the number to be the same for all rows. I tried the following:

data data; set data; want = ranuni(0) ; run;

But this gives different value for each row.

I also tried to generate a macro variable then pass the value to the dataset, but I am struggling to make it work. Can anyone teach me how to do it please?

I tried the following:

%let want1= %ranuni(0) ;

I also tried:

%let want1= %eval ( ranuni(0) );

data data;
set data;
want = &want1;
run;
2

2 Answers

2
votes

To set the same value on every observation use the RETAIN statement to prevent SAS from resetting the value when it starts the next iteration of the data step.

data want;
  set have;
  if _n_=1 then myvar = ranuni(0) ; 
  retain myvar;
run;

To use functions in macro code you need to use the %SYSFUNC() macro function.

%let mvar = %sysfunc(ranuni(0));

data want;
  set have;
  retain myvar &mvar ;
run;
1
votes

Use %sysfunc to code gen a fixed random number assigned within the DATA step.

data data; 
  set data;
  want = %sysfunc(ranuni(0));
run; 

Here is an SQL version using the same for comparison:

proc sql;
  alter table have add want num;
  update have set want=%sysfunc(ranuni(0));
quit;