2017-03-20 14 views
0

我創建了一個自定義函數來基於兩個輸入計算值。在循環中使用帶有2個輸入的函數以創建數據幀的輸入組合

# function 
info.theta <- function(theta, delta) { 
    P = 1/(1+exp(-1*(theta-delta))) 
    Q = 1 -P 
    1*P*Q 
} 

我想使用該函數來計算兩個感興趣序列的所有可能值組合的值。

# for each input of the function create sequences of values to explore 
thetas <- seq(-4, 4, by = .5) 
deltas <- seq(-4, 4, by = .5) 

我想和與列標記θ驅動,三角洲和信息,其中兩個theta和增量是在函數中使用的序列的值的數據幀到結束,並且信息是爲theta和delta的每個組合輸出函數。

我對如何執行最後一點不知所措,因爲這個級別的編碼對我來說是新的。我的預感可能是一個嵌套的循環。這顯然是不正確的,但是距離我可以開始的距離很近。我如何使用我描述的方式生成所需的數據框?

#nested for loop 

y <- NULL 
for(i in sequence) { 
    for(j in deltas) { 
    tmp <- info.theta(i, j) 
    y <- rbind(y, tmp) 
    } 
} 
y 
+1

呀,循環不超好玩一旦做起事情來炸燬。如果你不得不比較一些東西呢? – SeldomSeenSlim

回答

1

稍微改變你原來的功能:

info.theta <- function(theta, delta) { 
    P = 1/(1+exp(-1*(theta-delta))) 
    Q = 1 -P 
    data.frame(theta=theta,delta=delta, information=1*P*Q) 

} 

因爲data.frames比較涼爽。

現在:

td_grid<-expand.grid(thetas, deltas) 
info.theta(td_grid[,1],td_grid[,2]) 

結果:

theta delta information 
1 -4.0 -4.0 0.2500000000 
2 -3.5 -4.0 0.2350037122 
3 -3.0 -4.0 0.1966119332 
4 -2.5 -4.0 0.1491464521 
5 -2.0 -4.0 0.1049935854 
6 -1.5 -4.0 0.0701037165 
7 -1.0 -4.0 0.0451766597 
8 -0.5 -4.0 0.0284530239 
9  0.0 -4.0 0.0176627062 
10 0.5 -4.0 0.0108662297 
11 1.0 -4.0 0.0066480567 
+0

完美。希望隨着我的編碼進步,我將學會更好地表達我的目標,並且能夠在來到這裏之前更輕鬆地解決這些問題。 'expand.grid'看起來像是一個非常簡單的解決方案,如果我能更清楚地表達我的問題,我可以發現它。 – bfoste01

+1

是的,我在上面添加了一條評論,但是我會在這裏包含它。真的儘可能避免循環。你可以使用'apply()'函數組來更簡潔,有效,更快速的代碼。另外,如果你想獲得更好的效果,你可以在函數中包含'expand.grid()'片段,這樣它就只需要兩個向量並輸出一個你喜歡的數據幀。 – SeldomSeenSlim

2

您可以使用outer獲得價值矩陣:

outer(thetas,deltas,info.theta) 
相關問題