2017-07-19 42 views
2

這裏第一次提交的每個循環迭代的結果填充一個對象。我最近表示與R合作,希望我能在某個問題上得到一些幫助。這個問題可能很容易解決,但我一直無法自己找到答案,我的研究也沒有成功。使用R

基本上我需要創建一個基於循環輸入的單個對象。我有7個模擬資產返回,這些對象包含我運行的模擬結果。我想匹配每個對象的列並組合一個(即每列1形成一個對象),這將用於一些計算。最後,每次迭代的結果應存儲在一個單獨的對象上,該對象必須在循環外部可用,以供進一步分析。

我創建了以下循環,問題是隻有最後一次迭代的結果才寫入最終對象。

# Initial xts object definition 
iteration_returns_combined <- iteration_returns_draft_1 


for (i in 2:10){ 

    # Compose object by extracting the i element of every simulation serie 
    matrix_daily_return_iteration <- cbind(xts_simulated_return_asset_1[,i], 
             xts_simulated_return_asset_2[,i], 
             xts_simulated_return_asset_3[,i], 
             xts_simulated_return_asset_4[,i], 
             xts_simulated_return_asset_5[,i], 
             xts_simulated_return_asset_6[,i], 
             xts_simulated_return_asset_7[,i]) 

    # Transform the matrix to an xts object 
    daily_return_iteration_xts <- as.xts(matrix_daily_return_iteration, 
             order.by = index(optimization_returns)) 

    # Calculate the daily portfolio returns using the iteration return object 
    iteration_returns <- Return.portfolio(daily_return_iteration_xts, 
             extractWeights(portfolio_optimization)) 

    # Create a combined object for each iteration of portfolio return 
    # This is the object that is needed in the end 
    iteration_returns_combined <<- cbind(iteration_returns_draft_combined, 
             iteration_returns_draft) 

} 

iteration_returns_combined_after_loop_view

可能有人請幫我解決這個問題,我將非常感謝的任何信息任何人都可以提供。

謝謝, R-新秀

+0

請改正過去的錯字你的代碼行「<< - 」。此外,沒有對象,如iteration_returns_draft –

+0

謝謝!它似乎現在工作 –

+1

@RajPadmanabhan,這不是一個錯字。在R. – Parfait

回答

0

通過查看代碼,我推測該錯誤是在你的for循環的最後一行。

iteration_returns_draft_combined 

從未定義過,所以它被假定爲NULL。實際上,您只能將來自每次迭代的結果列綁定到NULL對象。因此,最後一個循環的輸出也被列綁定到NULL對象,這就是您所觀察到的。請嘗試以下操作:

iteration_returns_combined <- cbind(iteration_returns_combined, 
            iteration_returns) 

這應該有效,希望!

0

考慮sapply和避免擴大循環中的對象:

iteration_returns_combined <- sapply(2:10, function(i) { 

    # Compose object by extracting the i element of every simulation serie 
    matrix_daily_return_iteration <- cbind(xts_simulated_return_asset_1[,i], 
             xts_simulated_return_asset_2[,i], 
             xts_simulated_return_asset_3[,i], 
             xts_simulated_return_asset_4[,i], 
             xts_simulated_return_asset_5[,i], 
             xts_simulated_return_asset_6[,i], 
             xts_simulated_return_asset_7[,i]) 

    # Transform the matrix to an xts object 
    daily_return_iteration_xts <- as.xts(matrix_daily_return_iteration, 
             order.by = index(optimization_returns)) 

    # Calculate the daily portfolio returns using the iteration return object 
    iteration_returns <- Return.portfolio(daily_return_iteration_xts, 
             extractWeights(portfolio_optimization)) 
}) 

而且如果需要的列綁定第一向量/矩陣,這樣做的算賬:

# CBIND INITIAL RUN 
iteration_returns_combined <- cbind(iteration_returns_draft_1, iteration_returns_combined)