[R] Translating a basic Python script into R

sun shine phaedrusv at gmail.com
Sat Dec 28 16:46:40 CET 2013


Hi

I am attempting to translate some of the models that Donella Meadows 
wrote about in her book "Thinking in systems" into code. Originally, I 
had wanted to do this in Python, but thought that it would be fun to see 
if it is feasible to do so in R, especially given the plotting capacity 
of R.

Meadows describes a very simple example of a stock and flow: 50 gallons 
of water in a bath tub - drain out at a rate of 5 gal/ minute and then 
turn on the faucet after five minutes which flows at 5 gal/ min. The 
outcome is obviously that after 5 minutes, the bath tub will maintain a 
steady stock of 25 gal thereafter.

My basic code in Python looks like this:

====Python code=====

stock = 50
time = 1
inflow_a = 0
inflow_b = 5
outflow = 5

x = [stock]
y = [time]

print "Model of inflow and outflow rates of water"
print "version 3"
print

print stock
while time <= 5:
     stock = (stock - outflow) + inflow_a
     time += 1
     y += [time]
     x += [stock]
     print stock
     if stock == 30:
         print "Faucet turned on"

while time >= 6 and time <= 9:
     stock = (stock - outflow) + inflow_b
     time += 1
     y += [time]
     x += [stock]
     print stock

print "Volume in tub stabilises at %d gallons over %d minutes" % (stock, 
time)
print x
print y
==== end code====

I want to translate this into an equivalent script in R.

After some searching around, I found how to set up a while loop, and 
constructed the first section, like this:

======R code======

while(time <= 10) {
   if time <= 5
   stock <
   time <- time + 1
   print(time)
}

===== end code =====

However, what I would like to learn how to do is to nest the if 
conditions in a way similar to that given in the Python code.

I'm sure that there must be some very elegant way to do this, but I 
cannot find out how to do so in any of the books I have, nor do my web 
searches throw back anything useful (I suspect that I'm not phrasing the 
question properly).

Can someone please offer a few suggestions about ways that I could 
translate the Python script into R so that I can then run a plot as well?

Many thanks in anticipation.

Sun



More information about the R-help mailing list