Finger Exercise: Throwing two Dice in R using the rpanel Package

After a period of examinations I needed to fresh up some R-vocabulary (the exact syntax) because I started to mix it up with other programming languages’ syntax. And here is my result: A dice game simulation. Not very innovative, not very difficult, but I suppose it could be quite useful for people being new to R as an easy example of how programming in R may work. Furthermore, it is an application of the nice rpanel package.

Dice Game with the rpanel package

For this program being very simple I skipped most comments on the code – but will add some more in the near future. The variables should be quite self-explaining. If not, feel free to write a comment. Of course more experienced programmers are welcomed to improve the code. 🙂

Usage: Run the code in R, use the sliders of the panel to choose the number of dice to throw, the number of throws and hit the Throw! button.

This small program enables you to investigate or illustrate, respectively, some aspects of convergence or simply to get a feeling for your chances to win your next dice game. Feel free to use the program for didactical purposes if you find it useful (see the license in the footer of this page). If you want to have reproducable results set a random number seed of your choice by using the set.seed() function implemented in R.

Happy R-ing.

The code:

#A dice game by Christian Theel



     for (x in 1:ndice) {

     for (i in 1:nthrows){
          for (j in 1:ndice){
               for (k in 1:6){
                    if ((k-1)/6 <= throws[i,j] && throws[i,j] < k/6) {throws[i,j]<-k}

     frequs<-table(dicesum) #compute point frequencies of dice sums

     relfrequs<-frequs/nthrows #compute relative frequencies

     par(mar=c(5, 4, 4, 4) + 0.1)

     barplot(relfrequs,col="lightblue",ylim=c(0,max(relfrequs)+0.005),main="Dice Experiment",xlab="Sum of Dice 
             Points",ylab="Relative Frequency",yaxt="n") #barplot with relative frequencies

     axis(side=4,at=tickmarks,labels=tickmarks*nthrows) #right-hand side y-axis with absolute frequencies
     mtext("Absolute Frequency", side = 4,padj=3)
     #grid(nx=NA,ny=NULL) #optional grid
     panel # call the panel!!!!!!!, otherwise you get "Error in panel$intname : $ operator is invalid for atomic vectors"

panel = rp.control(title = "Dice Game by Christian Theel (",size=c(500,500))

rp.slider(panel,nthrows, 1,1000,action = I, showvalue = TRUE, title = "Number of throws", resolution=1)

rp.slider(panel,ndice, 1,10,action = I, showvalue = TRUE, title = "Number of dice", resolution=1)

rp.button(panel, action = dicegame, title = "Throw!")

One thought on “Finger Exercise: Throwing two Dice in R using the rpanel Package

Leave a Reply

Your email address will not be published. Required fields are marked *