2014-11-25 92 views
0

我正在循環內進行計算。我想在迭代達到一定數量時更改計算。我一直試圖在第一個循環內運行另一個循環,以根據需要更改計算。這可能是完全不正確的方法。建議歡迎。在循環中循環以在特定迭代後臨時修改計算

u=seq(0,4,length=10) 
v=dexp(u,rate=1) ##exponential decay 
w=0.87*v #the vector that I want to apply to calculations 
x=25 #the iteration where I want to start altering the main loop calcs, from here to here + length(w 


test=data.frame(seq(1,150,2),seq(151,300,2))##some data 
for(y in 1:(length(test))) 
{ 
res=test[,1]*test[,2]###the main calculation of the loop, simplified 
for(z in x:x+(length(w)))###on iteration x=25 start this secondary loop after running the first loop 
{ 
res[z+1]=res[z]-(res[z]*w[z]) 
} 
} 
plot(cumsum(res)) 

按預期這不循規蹈矩,我正在尋找的增長下降或在x = 25在圖上的平坦化。

+1

這段代碼遇到了一些問題...'length(test)'返回'2',因爲data.frame的長度是它的列數; '25:25 + 10'返回'35',因爲在'+'運算符之前計算':'運算符(所以你需要'25:(25 + 10)')。 R中的許多函數都是矢量化的,所以我們可以完全避免這些循環。 – jbaums 2014-11-25 09:27:34

+0

如果包含您的預期輸出(如果有幫助,請縮短示例數據)會很好。 – jbaums 2014-11-25 09:29:53

回答

0

從一個迭代25起以下更改算了一筆賬:

u=seq(0,4,length=10) 
v=dexp(u,rate=1) 
w=0.87*v 
test=data.frame(seq(1,150,2),seq(151,300,2)) 
res <- numeric(length=75) 

for(y in seq(nrow(test))) 
{ 
    ifelse(y < 25, res[y] <- test[y,1]*test[y,2], res[y] <- NA) 
} 
res[is.na(res)]<-res[24] 

res2 <- as.data.frame(res) 
res2 <- sweep(res2,MARGIN=2,w,`*`) 
res2 <- as.numeric(as.matrix(res2)) 

res <- append(res[1:24],res2[25:75]) 

plot(cumsum(res)) 

什麼是你想以w辦?我已經回收了迭代25中的矢量。