<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/antipredator-behavior-with-r-or-why-wildebeest-should-stay-together/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://allthiswasfield.blogspot.com/2018/07/antipredator-behavior-with-r-or-why.html"> long time ago...</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div></div>
<p></p>
<div></div>
<div>Hi there! </div>
<div></div>
<div> In 2010, when I was studying my Biology Degree at Universidad Complutense in Madrid, I fell in love with a documentary miniseries called <a rel="nofollow" href="https://en.wikipedia.org/wiki/Great_Migrations" target="_blank">Great Migrations</a>(<a rel="nofollow" href="http://www.nationalgeographic.com.au/tv/great-migrations/" target="_blank">National Geographic</a>). Their episodes talk about awesome migrations of animals around the globe. One of these chapters is “Great Migrations: Science Of Migrations”. It shows how scientists study the patterns and processes of animal migration. One of these researchers is <a rel="nofollow" href="https://www.uoguelph.ca/ib/fryxell" target="_blank">John Fryxell</a>, from Gelph University in Canada. John explains how mathematical models can help to understand movement patterns. Through simulations, he shows how wildebeests maintaining a clustered movement pattern can more effectively avoid to be hunted by a virtual lion (<a rel="nofollow" href="https://www.youtube.com/watch?v=Fa0rxb_LbfM" target="_blank">here</a> is the Spanish version in YouTube). I have to confess that each time I see those images, I think that I would be completely fulfilled with this kind of jobs.</div>
<div></div>
<div></div>
<div></div>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-s-sAxqBawaQ/W1Ysm0xr77I/AAAAAAAAARs/IyxYot7SI68e-df7s1mb9SOrqxezqQj8ACLcBGAs/s1600/random_cluster.gif?ssl=1" target="_blank"><img border="0" src="https://i0.wp.com/1.bp.blogspot.com/-s-sAxqBawaQ/W1Ysm0xr77I/AAAAAAAAARs/IyxYot7SI68e-df7s1mb9SOrqxezqQj8ACLcBGAs/s400/random_cluster.gif?resize=450%2C690&ssl=1" data-original-width="450" width="450" data-original-height="690" data-recalc-dims="1"></a></div>
<div></div>
<div></div>
<div>I modified a little bit my previous “go” function to reproduce the experiment shown by John. This is a small tribute to this documentary series and to all those people who inspire and motivate us and arouse our curiosity, as John.</div>
<div></div>
<div>You can find the code to perform these simulations with R below. To perform the gif of this post, you can follow <a rel="nofollow" href="http://allthiswasfield.blogspot.com/2017/12/p-margin-bottom-0.html" target="_blank">this procedures</a>. And if you want to be updated with my posts, find me on my new Twitter account <a rel="nofollow" href="https://twitter.com/javi_ferlop" target="_blank">@javi_ferlop</a></div>
<div></div>
<div>That is all, enjoy!</div>
<div></div>
<div></div>
<div></div>

<p></p>
<pre><code> # First, we prepare packages and raster layers to be used later. We also load  <br> # the species class to define the hunter inital location and his environmental  <br> # optimum (grass cover in this case), as in previous posts.  <br>   <br> library (raster)  <br> library(dismo)  <br>   <br> gc &lt;- raster(nrows = 100, ncols = 100, xmn = 0, xmx = 100, ymn = 0, ymx = 100)  <br> gc[] &lt;- runif(10000, -80, 180)  <br> gc &lt;- focal(gc, w = matrix(1, 5, 5), mean)  <br> gc &lt;- focal(gc, w = matrix(1, 5, 5), mean)  <br>   <br> species &lt;- setClass(&quot;species&quot;, slots = c(x = &quot;numeric&quot;, y = &quot;numeric&quot;,   <br>                      opt = &quot;numeric&quot;))  <br>   <br> # Then we will load the hunt function. This is pretty similar to my previous  <br> # &quot;go&quot; function. However, I added a &quot;preys&quot; attribute, a set of locations  <br> # of available preys. After each movement of the hunter, the function checks  <br> # if the hunter is in the same cell as any prey. If yes, it records this  <br> # location and delete this prey from the available preys. The output is a 4  <br> # column dataframe: the first two are the location of the hunter at each  <br> # iteration. The last two show if there is any capture at this iteration.   <br>   <br> hunt &lt;- function (sp, env, n, sigma, theta_x, alpha_x, theta_y, alpha_y, preys) {  <br>  track &lt;- data.frame() #create an empty data.frame to store each step coordinates  <br>  track[1,1] &lt;- sp@x  #the first position will be the initial position of the specimen defined by the species class  <br>  track[1,2] &lt;- sp@y  #the first position will be the initial position of the specimen defined by the species class  <br>  hunted &lt;- data.frame()#create an empty data.frame to store hunted preys  <br>    <br>    <br>  for (step in 2:n) {  <br>     <br>   #update preys locations   <br>     <br>   prey_cells &lt;- cellFromXY(env, as.matrix(preys + step))  <br>     <br>   #First, the function searches in the adjacent cells what have the value that best fits with the species requirements  <br>   lon_candidate&lt;--9999  <br>   lat_candidate&lt;--9999  <br>   #randomization/atraction routine  <br>   while ( is.na(extract(env, matrix(c(lon_candidate,lat_candidate),1,2)))) {  <br>    lon_candidate &lt;- track[step-1,1]+ (sigma * rnorm(1)) + (alpha_x * ( theta_x - track[step-1,1]))  <br>    lat_candidate &lt;- track[step-1,2]+ (sigma * rnorm(1)) + (alpha_y * ( theta_y - track[step-1,2]))  <br>   }  <br>     <br>   neig &lt;- adjacent(env,   <br>            cellFromXY(env, matrix(c(lon_candidate,  <br>                        lat_candidate), 1,2)),   <br>            directions=8, pairs=FALSE )  <br>     <br>   options &lt;- data.frame()  <br>   for (i in 1:length(neig)){  <br>    options[i,1]&lt;-neig[i]  <br>    options[i,2]&lt;- sp@opt - env[neig[i]]  <br>   }  <br>   option &lt;- c(na.omit(options[abs(options$V2) == min(abs(na.omit(options$V2))), 1 ]),   <br>         na.omit(options[abs(options$V2) == min(abs(na.omit(options$V2))), 1 ]))  <br>     <br>   new_cell &lt;- sample(option,1)  <br>   new_coords &lt;- xyFromCell(env,new_cell)  <br>     <br>   track[step,1] &lt;- new_coords[1]  <br>   track[step,2] &lt;- new_coords[2]  <br>     <br>   if (new_cell %in% prey_cells) {  <br>    hunted[step,1] &lt;- new_coords[1]  <br>    hunted[step,2] &lt;- new_coords[2]  <br>    preys &lt;- preys[-match(new_cell,prey_cells),]  <br>   }  <br>   else {  <br>    hunted[step,1] &lt;- NA  <br>    hunted[step,2] &lt;- NA  <br>   }  <br>  }  <br>  return(cbind(track,hunted))  <br> }  <br>   <br> # Later we define our predator, in this case, a lion! The inital possition will  <br> # be at the middle of the space (50,50). We will also select the environmental  <br> # optimum of our lion, 60% of grass cover (our lion hates bare ground xD)  <br>   <br> lion &lt;- species(x= 50, y =50, opt= 60)  <br>   <br> # Now, we will set the locations of a bunch of wildebeests using &quot;randomPoints&quot;   <br> # from &quot;dismo&quot; package. As our wildebeests will be running around, we will   <br> # initially locate them at the bottom left.  <br>   <br> r &lt;- raster(nrows=500, ncols=500, xmn=-500, xmx=0, ymn=-500,ymx=0)  <br> wb &lt;- randomPoints(r, 10000)  <br>   <br> # Here we have our wildebeests ready to run!  <br>   <br> plot(wb)  <br>   <br> # Let start the hunting!   <br>   <br> hunting &lt;- hunt(lion, gc, 600, 2, 0, 0, 0, 0, wb)  <br>   <br> # In &quot;hunting&quot; object is stored each location of our lion during the 600   <br> # iterations, as well as each time she catches a wildebeest. To see only the   <br> # catches, you can use:  <br>   <br> na.omit(hunting)  <br>   <br> # Pretty awesome, right? But, what happens if we group our wildebeests in   <br> # clusters? To do it, we will define another small function that creates   <br> # clusters of points:  <br>   <br> clus &lt;- function(n,m1,m2){  <br>  df&lt;-data.frame()  <br>  for (i in 1:n){  <br>     <br>   a &lt;- rnorm(100,m1[i],1)  <br>   b &lt;- rnorm(100,m2[i],1)  <br>   df &lt;- rbind(df,data.frame(a,b))  <br>  }  <br>    <br>  return(df)  <br> }  <br>   <br> wb_clustered &lt;- clus(100, runif(100,-500,0),runif(100,-500,0))  <br>   <br> # Look at the wildebeests locations now!  <br>   <br> plot(wb_clustered)  <br>   <br> # Ok, let's go again!  <br>   <br> hunting_clustered &lt;- hunt(lion, gc, 600, 2, 0, 0, 0, 0, wb_clustered)  <br>   <br> # Let's chek how many catches he have now:  <br>   <br> na.omit(hunting_clustered)  <br>   <br> # And comparing both strategies...  <br>   <br> nrow(na.omit(hunting))  <br> nrow(na.omit(hunting_clustered))  <br>   <br> # ...looks like wildebeests should stay together!!  <br> # You can run these simulations n times to see if the results are robust.  <br>   <br> # Finally we can print each iteration to make a cool gif <img alt="😉" src="https://s.w.org/images/core/emoji/2.4/72x72/1f609.png" class="wp-smiley">  <br>   <br> for (i in 1:600) {  <br>  id &lt;- sprintf(&quot;%03d&quot;, i)  <br>  png(paste(&quot;lion1_&quot;,id,&quot;.png&quot;, sep=&quot;&quot;), width=1300, height=690, units=&quot;px&quot;,  <br>    pointsize = 16)  <br>    <br>  par(mfrow=c(1,2))  <br>    <br>  plot(gc, xlim = c(6,94), ylim = c(6,94), main=&quot;random&quot;, legend=FALSE)  <br>  points(hunting[i,1:2], cex=1.5, col=&quot;red&quot;, pch = 0, lwd =3)  <br>  points(hunting[1:i,3:4], cex=1, col=&quot;blue&quot;, pch = 3, lwd =3)  <br>  points (gnu +i, pch = 20)  <br>    <br>  plot(gc, xlim = c(6,94), ylim = c(6,94), main=&quot;clustered&quot;, legend=FALSE)  <br>  points(hunting_clustered[i,1:2], cex=1.5, col=&quot;red&quot;, pch = 0, lwd =3)  <br>  points(hunting_clustered[1:i,3:4], cex=1, col=&quot;blue&quot;, pch = 3, lwd =3)  <br>  points (gnu_clustered +i, pch = 20)  <br>    <br>  dev.off()  <br> }  <br>   <br>   <br></code></pre>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://allthiswasfield.blogspot.com/2018/07/antipredator-behavior-with-r-or-why.html"> long time ago...</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/X0mpMXkexNc" height="1"></a></div>