2017-07-19 98 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)