I never take no for an answer from the computer … or, how to get an R function to return two values

Whenever I run a batting order simulation, I test all 362,880 possible combinations.  Simulating all those combinations 1000 times each takes 8 hours using an 8-core, 4 GHz, 32GB RAM computer.

As it stands, I can return only one value (in this case: total runs) from the function.  As part of determining if the simulation was working correctly, I thought it might be interesting to see how many batters came to the plate in a 9-inning simulation.

So, I wanted to return both runs and batters each time a simulation is run.  However, an R function can return only one value.  I poked around and found out that you can return a list as a way to return more than one value … but have been unable to make it work.  Part of the problem (I think) is that I am using ‘replicate’.

Here is the very much simplified version of what is being done in R:


create the cluster

#read in the list of all possible lineup combinations
#do the whole thing using parellel processing (8 processors)

results_lineups <- foreach(i = 1:combos) %dopar% {

#read in the transition-state-changes table for the combination being simulated
#simulate the combination 1000 times

results <- replicate(1000, simulate.lineups.game( variables list ))
results_lineups[i] <- mean(results)
#print the results to a csv file and stop the cluster


I’ve tried several different bits of syntax but nothing has worked.  So time for a brainstorm …

I’ve used CONCATENATE in Excel to create unique strings from two pieces of information and I wondered if I couldn’t create an artificial value that would do the same thing.

So, I modified the function to determine total runs and total batters and created a single value by:

total = (total.runs * 10000) + (batters/10000)

which creates a single value, for example: 40960.0038034

Then all I have to do is deconstruct the returned value into it’s component parts, in this case: 4.096 runs and 38.034 batters for that particular simulation.

So, it works, but I still wonder if there isn’t a way to return two values in R.  If anyone knows, or can point me in the right direction, I’m all ears … :-þ