Hello experts, I tried to figure out this exercise for running a macro loop, but as I am still new to this I wanted to check to make sure I was doing this correctly! I think my graph might be wrong. Here are the instructions:
Run a macro loop to illustrate the Law of Large Numbers. This is what you need to do: (a) Generate 1, 2, 3, 4, 5, …, n Bernoulli(p) random variables and compute the means of 1, 2, 3 ,4,5, …, n variables. Generate the variables and do the computations within the same loop (cf. the code we studied in class). (b) Plot the means to show that they converge to p. (c) Create a macro loop which has n and p as arguments.
Here is my code:
%macro loop1(p,n);
data Bernoulli;
do j=1 to &n;
u=rand("Bernoulli",&p);
output;
keep u;
end;
run;
data exercise2;
set Bernoulli;
acc+u;
time=_N_;
xbar=acc/time;
run;
proc univariate data=Bernoulli noprint;
var u;
output out=stats mean=xbar;
run;
proc append base=Bernoulli data=stats;
run;
%end;
symbol interpol=join;
proc gplot data=exercise2;
plot xbar*time/vref=&p;
run;
%mend;
%loop1(0.6,600);
Please help! Thank you!
Show us the graph.
Describe why you think it is wrong.
You may want to show us the code of your loop that actually ran. As posted it throws a macro compiler error:
709 %macro loop1(p,n); 710 data Bernoulli; 711 do j=1 to &n; 712 u=rand("Bernoulli",&p); 713 output; 714 keep u; 715 end; 716 run; 717 data exercise2; 718 set Bernoulli; 719 acc+u; 720 time=_N_; 721 xbar=acc/time; 722 run; 723 proc univariate data=Bernoulli noprint; 724 var u; 725 output out=stats mean=xbar; 726 run; 727 proc append base=Bernoulli data=stats; 728 run; 729 %end; ERROR: There is no matching %DO statement for the %END. This statement will be ignored. 730 symbol interpol=join; 731 proc gplot data=exercise2; 732 plot xbar*time/vref=&p; 733 run; 734 %mend;
Please post code or log entries in a code box opened with the forum's {I} or "running man" icons to preserve formatting.
As posted your Exercise2 data set would have been something not generated by the shown code.
I think you need SAS/IML , if you want simulate many variables.
And @Rick_SAS wrote a couple of blogs about this topic .
One of them I remembered is guessing weight of a pumpkin at Christmas .
There is display just one variable .
data have;
call streaminit(123);
do i=1 to 100;
x=rand('bern',0.2);
output;
end;
run;
data have;
set have;
sum+x;
mean=sum/_n_;
run;
proc sgplot data=have;
series x=i y=mean;
refline 0.2/axis=y;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.