[英]apply function instead of nested loop with if statements
這是顯示我需要計算的圖像 。 對不起,圖片中的total_r實際上是代碼中的test_gain,而pic中的gamma是指代碼中的alpha(對不起)。 同樣在圖像中我停止在t = 3計算,但實際上我想計算它直到最后一個值為0.6。
我很擅長使用apply系列函數。 我通常使用循環,但我聽說使用apply函數而不是嵌套for循環要快得多。 我嘗試了幾個教程,但仍然無法用apply函數替換我的嵌套for循環。 任何幫助將不勝感激,下面是我試圖改變的代碼。
基本上這就是我要做的事情:數據的第一行:從列的列+ alpha * nextvalue獲取值(第2行)+ alpha ^ 2 * column(row3)的nextvalue + alpha ^ 3 * next列(row4)的值等等,直到最后一行。 每次我增加Alpha的力量。
所有這些計算都是第一行。 現在對於第二行,我將忽略列中的第一個值,但將以相同的方式獲取所有后續值。 下面是我的代碼工作正常,但執行時間太長。
#value of alpha
alpha <- 0.85
# test_gain is a vector containing values from a column belonging to a data frame
test_gain <- testdata$Total_rew
# initialise the variables
s = 0
d = rep(0,nrow(testdata))
for (i in 1:nrow(testdata[1:4999,])){
d[i] = test_gain[i]
for (s in (i+1):nrow(testdata)){
d[i] = d[i] + alpha^(s-i) * test_gain[s]
if (alpha^(s-i) < (10^-5)) {next()}
}
}
關鍵是要生成的尺寸的上三角矩陣N
冪級數的alpha
其中N
是行數testdata
看起來像這樣:
1 alpha alpha^2 alpha^3 ... alpha^(N-1)
0 1 alpha alpha^2 ... alpha^(N-2)
0 0 1 alpha ... alpha^(N-3)
0 0 0 1 ... alpha^(N-4)
... ...
0 0 0 0 1
然后,計算只是一個矩陣乘以列testdata$Total_rew
。
要生成這個上三角矩陣(改編自這個SO問題/答案 ):
## This will work for both nrow(testdata) is odd and even
nr <- ceiling(nrow(testdata)/2 - 1)
mat <- outer(alpha^(-nr:nr), alpha^(-nr:nr))
## reverse the columns
mat <- mat[,rev(seq.int(ncol(mat)))]
## what we want is in the lower triangular, so set the upper triangular to zeroes
mat[upper.tri(mat)] <- 0
## take the transpose so what we want is now upper triangular
mat <- t(mat)
然后,
d <- mat %*% testdata$Total_rew
另請注意,您不需要在上面的最后一步中轉置mat
。 如果你不在上面的最后一步中轉置mat
,這也會得到相同的結果:
d <- testdata$Total_rew %*% mat
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.