Getting started with R

The best way to get started with R is to simply play around with some code and get a feeling for some of the cool things you can do with it. The first time I got introduced to R, was through Conway’s game of life. This is simple population model which can create some pretty animations. I’m going to show you how to get one of these animations using R based on some code on the blog Are you cereal? that I’ve altered. This is what it should look like at the end:


Installing R

You can install R here: for windows for mac

Once installed, you will need to open R and create a new script and paste the code (at the bottom of page). Here’s how you create a new script:


Now that you have your script, you can paste the code (below in blue)  in your new script file. Use Ctrl+r to run your highlighted code in R from your script.

Conway’s Game of Life

To create an environment for your species , you need to create a grid of cells and then populate these cells with individuals. This can simply be done using ones and zeros:

1= an individual

0= no individual

To make the model dynamic, you can add timesteps. For each timestep, you consider each cell and what is happening in it’s neighbouring cells. Simple rules can then be applied to each cell. (please note I have modified these slightly from Conway’s game of life)

  • If your cell is populated (=1) and you have 1, 2 or 3 neighbours you can keep living
  • If your cell is populated (=1) and you have 0 neighbours you die alone
  • If your cell is populated (=1) and you have more than 3 neighbours it’s too crowded and you die
  • If your cell is not populated (=0) and you have 3 neighbours you become alive due to your neighbours reproducing

You therefore need to calculate what is happening in your neighbourhood for each model iteration or timestep to determine what is going to happen in the next time step.

You will note that with a grid of cells, the cells at the edges of the grid do not have any neighbours. We therefore need to adapt the code for this by creating neighbours from the cells at the other side of the grid. You can ignore this part of the code for now.

Implement the game of Life in R

Paste the below code into your new R script and modify the working directory (first line of code). You will notice a lot of #. # are used to comment out code. This means that R will not read anything after a #. To Run the code press Ctrl+a then Ctrl+r


# set your working directory: this is the pathway to the directory to save your data in

# you will only need to do this step once. Once you execute this command, R will ask you # which mirror to use, choose one close by. After that put a # in front of the command
# library that allows the animated .gif export

#Create a function <- function(size, time, filename, StartPop){

# create X a size x size grid of cells filled up with binomially distributed individuals
X <- matrix(nrow=size, ncol=size)
#populate X with individuals from a binomial disturbution.
#The proportion of populated cells is determined by StartPop
X[] <- rbinom(size^2,1,StartPop)

  # We create a structure to save our data and export it later to the gif file
  storage <- array(0, c(size, size, time))

  #for every time step
  for (i in 1:time)
     # Create neighborhood matrices for N=North cell, E=East cell, S= South cell, W=West
     allW = cbind( X[,size] , X[,-size] )
     allNW = cbind(X[,size],rbind(X[size,-size],X[-size,-size]))
     allN = rbind(X[size,],X[-size,])
     allNE = cbind(rbind(X[size,-1],X[-1,-size]),X[,1])
     allE = cbind(X[,-1],X[,1])
     allSE = cbind(rbind(X[-1,-1],X[1,-1]),X[,1])
     allS = rbind(X[-1,],X[1,])
     allSW = cbind(X[,size],rbind(X[-1,-size],X[1,-size]))

     # Sum all the neighbouring cells to see how many individuals are present nearby
     Xneighbours <- allW + allNW + allN + allNE + allE + allSE + allS + allSW

     # Apply the rules of the game of life to our data
     Xnew <- X
     Xnew[X==0 & Xneighbours==3] <- 1
     Xnew[X==1 & Xneighbours<1] <- 0
     Xnew[X==1 & Xneighbours>3] <- 0
     X <- Xnew

     # save data for gif to make pretty animation
     storage[,,i] <- Xneighbours
   storage <- storage/max(storage) # scale the results to a 0-1 scale

   # write the results into an animated gif
   write.gif(storage, filename, col=”jet”, delay=5)

# now we can call the function so that the gif is created. Note that:
# size = the number of cells in your grid representing your environment
# time = the number of time steps/iterations you want your model to run for
# filename = the name you would like to give your file
# StartPop = is the proportion of grid cells with an individual at the beginning of a  simulation, time=300, filename=”conway.gif”,StartPop=0.07)

Playing around with the code

The last line of code is the function that you call to carry out the game of life. You no longer need to load the rest of the code into R and can simply play around with this one line of code. This allows you to change the model parameters. For instance you might change StartPop = 0.4. Further details about the model parameters can be found below:

  • size = the number of cells in your grid representing your environment. The bigger, the longer the model will take to run
  • time = the number of time steps/iterations you want your model to run for. The bigger, the longer the model will take to run
  • filename = the name you would like to give your file. Note that every time you run the function, your file will be re-written so you will want to change it’s name each time
  • StartPop = is the proportion of grid cells with an individual at the beginning of a  simulation and can have a value between 0 and 1

2 thoughts on “Getting started with R

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s