shuji shuji - 3 months ago 7
R Question

How can I assign the combination of possible values for some variables in R?

I am trying to do simulations with some variables changing their value in a range, is there a simpler way than creating a loop for each one of them?

This used to be my code on C++ (of course the loop was generated by another script so i could work faster)

int SMA = 9; //extern
double buyLotSize = .01; //extern
double sellLotSize = .01; //extern
int buySpreadMargin = 0; //extern
double minEquity=.6; //extern
int maxRisk=3000; //extern
int FastMAPeriod = 12; //extern
int SlowMAPeriod = 26; //extern
double Lot=.01; //extern
double lotLimit=.07; //extern
for(int SMA=3; SMA<33; SMA+=3)
for(double buyLotSize=0; buyLotSize<6; buyLotSize+=0.3)
for(double sellLotSize=0; sellLotSize<6; sellLotSize+=0.3)
for(int buySpreadMargin=0; buySpreadMargin<6; buySpreadMargin+=0.3)
for(double minEquity=0; minEquity<6; minEquity+=0.3)
for(int maxRisk=3000; maxRisk<60000; maxRisk+=3000)
for(int FastMAPeriod=3; FastMAPeriod<33; FastMAPeriod+=3)
for(int SlowMAPeriod=3; SlowMAPeriod<33; SlowMAPeriod+=3)
for(double Lot=0; Lot<6; Lot+=0.3)
for(double lotLimit=0; lotLimit<6; lotLimit+=0.3)
{ sim[nsim].SMA=SMA;
sim[nsim].buyLotSize=buyLotSize;
sim[nsim].sellLotSize=sellLotSize;
sim[nsim].buySpreadMargin=buySpreadMargin;
sim[nsim].minEquity=minEquity;
sim[nsim].maxRisk=maxRisk;
sim[nsim].FastMAPeriod=FastMAPeriod;
sim[nsim].SlowMAPeriod=SlowMAPeriod;
sim[nsim].Lot=Lot;
sim[nsim].lotLimit=lotLimit;
sim[nsim].dosomething()
...


My plan is to to create a list with each variable value and range, but I am still too new to the language, and I cannot figure another way to use all the combinations without replcating the same loop, something like this would do the trick, I thought this kind of task would be simpler in R but I am not sure, I haven't found what I am looking for.

var1$range=range(0,3,.2)
var2$range=range(3,30,3)
for comb(var1,var2,...)
simulation{ dosomething(var1$value) dosomething(var2$value) }

Answer

expand.grid will return a data frame with all of the combinations of the input values. You would write a function that worked on a row of the data frame.

a <- seq(0, 1, 0.2)
b <- seq(0, 1, 0.5)

df <- expand.grid(a = a, b = b)

do_something <- function(a, b){
  #do something
  a + b
}

df$c <- do_something(df$a, df$b)

df
     a   b   c
1  0.0 0.0 0.0
2  0.2 0.0 0.2
3  0.4 0.0 0.4
4  0.6 0.0 0.6
5  0.8 0.0 0.8
6  1.0 0.0 1.0
7  0.0 0.5 0.5
8  0.2 0.5 0.7
9  0.4 0.5 0.9
10 0.6 0.5 1.1
11 0.8 0.5 1.3
12 1.0 0.5 1.5
13 0.0 1.0 1.0
14 0.2 1.0 1.2
15 0.4 1.0 1.4
16 0.6 1.0 1.6
17 0.8 1.0 1.8
18 1.0 1.0 2.0