[R] Beginner - simple simulation

Jacob van Wyk jlvw at na.rau.ac.za
Tue Mar 1 09:25:37 CET 2005


Hallo to everybody. I am new to the list and would appreciate some help
in a basic "first demo" of how to use R for simulating a simple game; I
would like my students to use R and this may stimulate their interest.

The problem is simply:

Two players (A and B) play the following game. Each player rolls a die
(fair, 6-sided) and they write down the result: say A rolls nA and B
rolls nB. If nA is even, A pays B $nB: if nA is odd, B pays A $nA (we
think of A paying B a negative amount). The amount that A pays B is a
random variable X. Find the expectation of X.

Theoretically it is 1/4 - B is ahead on average with 25c.

Would anybody be prepared to help a little. I want to avoid loops and
vectorize the computations, simulate the value of X for various sample
sizes and preparea basic plot to show that the average value of X
"converges" to 1/4.

I would start with, say,
sample(1:6,2,replace=T)
for one simulated roll of the two dice. I want to repeat this n times,
where n is, say, 10:2000 in steps of 10. Put the results in a matrix and
work columnwise - choosing when the first roll is even, selecting the
corresponding value of the second roll, and computing the payoff as
described, etc. But I need help to put this together.

In Matlab I would, for example, do the following to display the average
payouts of A and B:

c=1;
samplesizes=[10:10:2000];
for s=samplesizes
rolls=ceil(6*rand(s,2));
a_pays_b_index=find(mod(rolls(:,1),2)==0);
a_pays_b_value=rolls(a_pays_b_index,2);
b_pays_a_index=find(mod(rolls(:,1),2)==1);
b_pays_a_value=rolls(b_pays_a_index,1);
a_pays_average(c)=mean(a_pays_b_value);
b_pays_average(c)=mean(b_pays_a_value);
c=c+1;
end

Then do the plotting, etc. (One could also take differences, and so
on.)

I would really appreciate if anybody would be kind enough to help. I
thought it might be a nice example to introduce students (in general,
perhaps - because it is a kind of interesting game) to simulation in R.

Thank you !
Jacob
(PS Any credit would be respected, i.e. my students will know who
helped me with this introduction.)




Jacob L van Wyk
Department of Mathematics and Statistics
University of Johannesburg APK
P O Box 524
Auckland Park 2006
South Africa
Tel: +27-11-489-3080
Fax: +27-11-489-2832




More information about the R-help mailing list