[R] basic q re: parsing functions, declaration order

Gowder, Paul paul-gowder at uiowa.edu
Sat Apr 18 19:14:31 CEST 2015


Hi there, 

So I’m doing some serious coding in R for the first time—writing a strategic simulation to run for a few (or many) thousand iterations,* and doing so in proper functional programming form, i.e., with a bunch of wrapper functions calling other wrapper functions calling the stuff that does the real work.  So, like: 

simulate.strat <- function(runs) {
  results <- # blah blah blah
  for (i in 1:runs) {
  run.res <- c(i,outer.wrapper())
  rbind(results,run.res)
  }
  write.table(results, file="simul_results.csv", row.names=TRUE, col.names=TRUE, sep=",”) 
# bonus question: there’s probably a vastly more efficient way to do this final write, any suggestions welcomed
}

outer.wrapper <- function() {
  goods <- dist.goods()
  power <- dist.power()
# blah blah blah
one.run <- inner.wrapper(goods, power, subgroups.num, subgroups.dist, trust, trust.errorvar)
  return(one.run)
}

dist.goods <- function() {
  elite.goods <- sample(1000:4000, 1)
# blah blah blah 
  goods.dist <- c(elite.dist, mass.dist)
  return(goods.dist)
}

and so forth.  

I’m just putting it all in one source file, which I plan to load using source(), and then actual execution will be via console input > simulate.strat(number of runs), leave town for the weekend, hopefully come back to find a csv with a bunch of results. 

But I’m not quite sure how the parser works with respect to defining all these functions.  Do I have to define them from inside out like one would in python?  (So, on the code above, that would mean defining, say, dist.goods() and dist.power() first, then outer.wrapper(), then simulate.strat().)  Or is there a way to prototype them like one would in C?  Or--- and I really hope this is the answer so I don’t have untangle the tangled web of functions I’m writing— is R smart enough/lazy enough to accept that the function defined at line K can call a function defined at line K+N and not stress about it?  

thanks so much!  My google-fu is failing me on this one.

-Paul


* why on earth, you might ask, am I doing this in R, rather than C or something?  Because I have a ton of computing resources and a huge workload. CPU time is cheap and my time is expensive… 


More information about the R-help mailing list