查找调试时R中发生错误的位置

查找调试时R中发生错误的位置,r,debugging,for-loop,R,Debugging,For Loop,如何找出错误发生的位置 我有一个这样的双环 companies <- # vector with all companies in my data.frame dates <- # vector with all event dates in my data.frame for(i in 1:length(companies)) { events_k <- # some code that gives me events of one company at a time

如何找出错误发生的位置

我有一个这样的双环

companies <- # vector with all companies in my data.frame
dates <- # vector with all event dates in my data.frame

for(i in 1:length(companies)) { 
  events_k <- # some code that gives me events of one company at a time

  for{j in 1:nrow(events_k)) {
  # some code that gives me one event date at a time
  results <- # some code that calculates stuff for that event date

}

mylist[[i]] <- results # store the results in a list
}

公司如果没有明确的代码,我们很难知道我们可以运行什么,但我猜将代码更改为

 for(i in companies) { 
    for(j in dates) {
或者

 for(i in 1:length(companies)) { 
    for(j in 1:length(dates)) {
也许可以解决这个问题。请注意第二个循环中的
),如果不是,最好编辑示例,使其包含一些产生相同错误的代码/数据

要想知道它发生在哪里,您可以在代码中的适当位置添加
print(i)
或类似的内容。

我喜欢使用的是:

options(error = recover)
您只需在会话开始时运行一次(或将其添加到
.Rprofile
文件中)

之后,每次抛出错误时,都会显示导致错误的函数调用堆栈。您可以选择这些调用中的任何一个,就像您在
browser()
模式下运行该命令一样:您将能够查看调用环境中的变量并遍历代码


有关更多信息和示例,请访问
?recover

一种简单的方法是在每次循环运行中打印
i
&
j
,这样您就可以知道当它失败时…在第二个for循环中出现语法错误!您会遇到以下错误:
错误:意外'{'in:
。我相信这不重要,但是RStudio已经包含了一些调试工具。键入
traceback()
。另请参见
?debug
?trace
?browser
?recover
侧注:不要使用
来执行此循环。这是“拆分-应用-合并”的作业函数。查看程序包plyr、dplyr或data.table。如果您在RStudio中,错误时的
调试
下拉菜单选项
中断代码
非常方便。
错误时的
提供了查看
回溯
的选项,它显示了错误的原因和发生位置。它是这对处理错误很有用。哦,是的!实际上我使用了类似于你的第二种方法。谢谢。我编辑了这个问题!