【问题标题】:Iterative approach code in R to make more efficient? [closed]R中的迭代方法代码以提高效率? [关闭]
【发布时间】:2014-05-08 20:06:25
【问题描述】:

我正在使用 Merton 默认模型和复杂的迭代方法。

我已经准备好了我的 R 代码,但由于我是 R 的新手,它们似乎非常低效,从某种意义上说它们运行了将近 7 个小时。我的主要问题是我的 for 循环部分。

恳请您检查我的 R 代码并提供任何可以使我的 R 代码更高效的更正,即它们运行的​​时间更少 我在这里下载了所有数据和 R 代码: https://www.dropbox.com/sh/jlqvao40e5nvkev/AACpPdAdG67juhX9HoHPpiC1a

编辑: 下面的循环运行很多,也许你知道一些我可以在这里用while和for循环替换的函数,我想sappy可以工作但我不知道如何应用它:

  errors<-ddply( df5, .(id, BSheetyearlag), function(x) sum((x$iterK-x$iterK1)^2))

  df5<-as.data.frame(df5)
  df5<-join(df5, errors, by=c("id", "BSheetyearlag"))
  df5<-as.data.table(df5)
  for ( i in 1:nrow(errors)){
  while(errors$V1[i] >= 10^(-10)) {
  df5<-as.data.table(df5)
  df5[,iterK:= iterK1,by=c("id", "BSheetyearlag")] 
  df5[,assetreturn:=c(NA,diff(log(iterK))),by=c("id", "BSheetyearlag")] 
  df5[,rollsdasset:=rollapply(assetreturn, 249, sd, fill=NA, align='right')*sqrt(250), by=c("id", "BSheetyearlag")]
  df5[,iterK1:=(cap+LTD05*exp(-rfabsol)*pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250]))-rollsdasset[250])/pnorm(blackscholes(iterK,LTD05,rfabsol, 1,rollsdasset[250])),by=c("id", "BSheetyearlag")]
  df5<-as.data.frame(df5)
  errors$V1[i]<-sum((df5[df5$V1 %in% errors$V1[i],"iterK"]-df5[df5$V1 %in% errors$V1[i],"iterK1"])^2)
        }
        }

【问题讨论】:

  • 这个网站是针对特定问题的。
  • 我的问题在 for 循环部分,但为了整体理解,我下载了所有数据
  • 不要使用保管箱位置来显示问题。将问题的规模缩小到可以将代码和数据输入问题本身的程度。事实上,这个问题不适合 SO。
  • 建议您将其移至:codereview.stackexchange.com
  • 很抱歉,我的问题没有说清楚。我会尽量以好的形式呈现。

标签: r for-loop


【解决方案1】:

通常,R 提供了许多执行循环的函数。它们被称为apply 系列函数。具体语法和细节,在 R 控制台输入:

?apply

此外,这里有一些链接可以帮助您熟悉这些功能。

另外,由于您是 R 新手,您应该研究一下基础 R 附带的调试工具。

traceback() 
# - prints out the function call stack after an error occurs
# - does nothing if there's no error
# - only gives the most recent error- call right away

recover()   
# allows you to modify the error behavior so that you can
# browse the function call stack

debug()
# flags a function for "debug" mode which allows you to step
# through execution of a function one line at a time.

browser()
# suspends the execuction of a function wherever it is
# called and puts the function in debug mode.
# You can put this anywhere in the code and it will start there.

trace()
# allows you to insert debugging code into a function in
# in specific places

还有可以通过Rprof() 访问的R Profiler。使用?Rprof 查看它的文档。

【讨论】:

  • 非常感谢您的宝贵建议 +1
  • 我的荣幸。将来,请尝试具体说明瓶颈或错误。现在您已经拥有了执行此操作的工具,我非常希望您能够运行它。
猜你喜欢
  • 1970-01-01
  • 2010-10-27
  • 2012-04-26
  • 1970-01-01
  • 2015-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
相关资源
最近更新 更多