簡體   English   中英

如何為R中的某些變量分配可能值的組合?

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

我正在嘗試使用一些變量在一定范圍內更改其值來進行仿真,是否有比為每個變量創建循環更簡單的方法?

這曾經是我在C ++上的代碼(當然,循環是由另一個腳本生成的,所以我可以更快地工作)

 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() //start simulation
    ...

我的計划是創建一個包含每個變量值和范圍的列表,但是我對這門語言還太陌生,並且我無法找到另一種使用所有組合而不用重復同一個循環的方式,這種方法可以解決問題,我以為R中的這種任務會更簡單,但是我不確定,我沒有找到我想要的東西。

var1$range=range(min=0,max=3,step=.2)
var2$range=range(min=3,max=30,step=3)
for comb(var1,var2,...)
    dosomething(var1$value, var2$value) //simulation

expand.grid將返回一個包含所有輸入值組合的數據框。 您將編寫一個對數據框的一行起作用的函數。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM