R365: Day 40 – if else statements in for loops

My hand is still busted so I cant really type so well.

Modifying the code that we used in for loops, let us try to add in an if else statement

#based on code developed by Carol Hom
#a for loop to monitor the progress of a gut parasite
#pretend i had more than you initially, but i am fairly resiliant against the parasites
#set initial parameters for parasite populations
me.init=800;
you.init=10;
#set a vector to record the populations as the for-loop progresses
me=rep(1,100);
you=rep(1,100);
#set initial population. me is a vector so me[] tells you which point in the vector to set as the initial
me[1]=me.init;
you[1]=you.init;
#the for loop has to be of length me. One way to get around that is to set it to length(me) instead of 30
for (t in 2:length(me)){
 #set howthe pop will grow. you could also use me[1] instead of me.init
#insert an if statement that does an even coin flip
 if(rbinom(1,1,(1/2))>=1){
 me[t]=me[1]*(0.9)^t
 you[t]=you[1]*(1.1)^t
 } else {
#in this scenario, every other day (chosen at random) you are more resistant than I am
 me[t]=me[1]*(1.2)^t
 you[t]=you[1]*(0.9)^t
}
#always close the loops
 #catenulate time, pop me, pop you, and end the line
 cat(t,me[t],you[t],"\n");
 #dontforget to close out
}
#create a matrix called data by binding the two columns called me and you
data=cbind(log(me),log(you));
data;
#plot the log of the parasite loads in me and you
matplot(1:100,data,pch=20,25,xlab="time",ylab="log parasite load",type="b");

This leads to an oscillating dynamics for the model

Rplot09

because (net) you are more resistant, you end up having a lowe over all net number of parasites

What happens if it is not an even flip? Say 1 in 10 events are bad days for me? (changing the rbinom(…,prob=0.1)

Rplot10

similar dynamics! the frequency changes but the overall trend looks similar! very cool.

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s