RStudio调试代码

最新推荐文章于 2025-04-24 11:30:00 发布
banlucainiao 最新推荐文章于 2025-04-24 11:30:00 发布
阅读量1.4k 收藏 1
点赞数
分类专栏: Statistics and R
Statistics and R 专栏收录该内容
62 篇文章
订阅专栏

Debugging with RStudio


  • Introduction
  • Entering debug mode (stopping)
    • Stopping on a line
    • Stopping when a function executes
    • Stopping when an error occurs
  • Using the debugger
    • Environment pane
    • Code window
    • Console
    • Debugging commands
  • Special circumstances
    • Debugging outside functions
    • Debugging in packages
    • Debugging in Shiny applications
    • Debugging in R Markdown documents
  • Further Reading

Introduction

Debugging in R is a broad topic. In this article, we focus specifically on the R debugging tools built into RStudio; for more general advice on debugging in R (such as philosophy and problem-solving strategies), we recommend this resource from Hadley Wickham:

Debugging, condition handling, and defensive programming

In a very general sense, debugging is designed to help you find bugs by figuring out where the code is not behaving in the way that you expect. To do this, you need to:

  1. Begin running the code
  2. Stop the code at the point where you suspect the problem is arising, and
  3. Look at and/or walk through the code, step-by-step at that point.

We’ll look at these last two tasks in detail.

Entering debug mode (stopping)

In order to enter debug mode, you’ll need to tell R when you want to pause the computation. R doesn’t have a “pause now” feature (and most computations are so fast that such a feature would not be helpful!). Instead, you’ll want to “set your traps” prior to starting your computation.

There are several ways to do this; pick one that corresponds best to your problem.

Stopping on a line

Editor breakpoints

The most common (and easiest) way to stop on a line of code is to set a breakpoint on that line. You can do this in RStudio by clicking to the left of the line number in the editor, or by pressing Shift+F9 with your cursor on the desired line.

We call this an “editor breakpoint”. Editor breakpoints take effect immediately and don’t require you to change your code (unlike browser() breakpoints, below).

Editor breakpoints work by injecting some tracing code into the R function object. R function objects that include this tracing code have a red dot in the environment pane, indicating that they contain breakpoints.

If the function object doesn’t exist yet (for instance, because you haven’t called source() on the file), or the function object doesn’t match the contents of the editor (for instance, because you’ve changed the file since the last source()), the breakpoint will be deferred.

The circle outline indicates that RStudio is aware of the breakpoint, but that it hasn’t been injected. In most cases, you can source() the file to resolve the problem.

browser() breakpoints

The R function browser() halts execution and invokes an environment browser when it is called. You can put browser() anywhere in your code to stop at that point in the code for debugging. Here, for instance, it’s used to halt when a function is about to return TRUE:

Unlike an editor breakpoint, the browser() statement is actually part of your code, so it needs to be applied like any other code change in order to become active (by sourcing the containing document, rebuilding the containing package, reloading the Shiny application, etc.).

The environment browser invoked by browser() is the same one used in all of the other debugging facilities, so it can be considered the lowest-level debugging tool. Because the browser() statement requires no special tooling, it can be used in contexts where editor breakpoints won’t work.

browser() is also useful for creating conditional breakpoints. For instance, if you want to start debugging after hundreds of loop iterations:

for (i in 1:1024) {
  start_work()
  if (i == 512)
    browser()
  finish_work()
}

Stopping when a function executes

If you have the .R file corresponding to the code you want to debug, it’s easy to use editor breakpoints or browser() to add breakpoints to it. Sometimes, however, you don’t have the source file for the code you want to debug.

When this is the case, you can set a debug flag on the function you want to debug. You can think of this as setting a breakpoint before the very first statement in a function; it does not change the function itself, but it causes the debugger to activate immediately when the function is run.

Use the R function debugonce() to set the debug flag on a function. For instance, if you want to debug devtools::install():

> debugonce(devtools::install)

debugonce() sets a one-shot breakpoint–that is, the function will enter the debugger the very next time it runs, but not after that. If you want to debug a function every time it executes, call debug(...) on the function. Call undebug(...) on the function when you no longer want to debug the function each time it executes. We don’t recommend this pattern, since it can leave you trapped in the debugger for some special functions.

Stopping when an error occurs

If you’re diagnosing a specific error, you can have RStudio halt execution at the point where the error is raised. To do this, go to Debug -> On Error and change the value from “Error Inspector” to “Break in Code”.

To keep the the debugger from being invoked whenever any error anywhere happens, RStudio does not invoke the debugger if it looks like none of your own code is on the stack. If you find that this is excluding an error you want to catch, go to Tools -> Global Options and uncheck “Use debug error handler only when my code contains errors”.

If you really want to invoke the debugger on every error, always, this will do the job:

> options(error = browser())

This overrides RStudio’s error handler settings. Trapping every error will quickly become annoying, though, so be sure to use the Debug menu to change the erroroption back when you’re done troubleshooting (or turn off error handling entirely with options(error = NULL)

Using the debugger

Once your code is stopped, the IDE will automatically enter debug mode, in which a variety of tools for inspecting and altering the state of your program become available. We’ll look at each in turn.

Environment pane

Usually in R you’re interacting with the “global environment”, a list of named objects such as values, functions, and data. When you enter debug mode, the IDE begins viewing and interacting with the currently executing function’s environment instead. That means that the objects you see in the Environment pane belong to the currently executing function, and statements you enter in the Console will be evaluated in the context of the function.

The gray values are promises–in this case, function arguments that haven’t been evaluated yet.

Above the list of local objects in the Environment pane is a drop-list that shows you the “environment stack”. This shows you the inheritance chain for the active environment–that is, the list of places that will be searched to resolve variable names to values.

Most of the time it will include just the current function, the global environment, and some package namespaces, but if you’re writing a package or nesting functions, it’ll have additional entries. You can click any item in the droplist to see the contents of the corresponding environment.

If this all sounds confusing, don’t worry–most of the time you won’t need to dive into the environment stack! If you want to understand what’s going on under the covers, see Environments for a detailed look at how environments and inheritance work.

Traceback (Callstack)

The traceback shares space with the environment pane. It shows you how execution reached the current point, from the first function that was run (at the bottom) to the function that is running now (at the top).

This is called the “call stack” in most languages; RStudio refers to it as the “traceback” for symmetry with the R command traceback().

You can click on any function in the callstack to see the current contents of its environment and the execution point in the function’s code, if it can be determined. Note that selecting a frame in the callstack does not change the active environment in the console! If you need to do that, use recover() (described below).

Most of the time you’ll only be interested in looking at the portions of the callstack that contain your own code, so by default RStudio hides internal functions (i.e. those for which it does not have a corresponding .R file) in the callstack to keep it from becoming too verbose. The View Internals checkbox can be toggled to show or hide internal functions in the callstack. For instance, inside a tryCatch block, you can expand the internals to see R’s exception handling functions (shown in gray):

Code window

The code window shows you the currently executing function. The line about to execute is highlighted in yellow.

If RStudio can’t find a .R file that matches the function, it will show the code in the Source Viewer. This can happen either because no .R file exists or because the function object doesn’t match the definition in the .R file.

Console

While debugging, you’ll notice two changes to the R console. The first is that the prompt is different:

Browse[1]> 

This prompt indicates that you’re inside the R environment browser.

The R console while debugging supports all the same commands as the ordinary console, with a few differences:

  1. Statements are evaluated in the current environment–that is, if your function has a variable named x, typing x at the prompt will show you the value of that variable. (Try ls() at the prompt to see all the variables).
  2. Simply pressing Enter at the console will execute the current statement and move on to the next one. This is a convenient way to step through statements quickly.
  3. A variety of special debugging commands are available (described below)

If you want to interact with a different function’s environment at the console, use recover() to display a list of running functions, from which you can select.

The second is that there’s a new toolbar on top of the console:

This toolbar provides convenient buttons that send the special debug control commands (see table below) to the R console. There’s no difference between using the toolbar and entering the commands at the console directly, so it’s helpful to learn the command shortcuts if you spend much time debugging.

Debugging commands

CommandShortcutDescription
n or EnterF10Execute next statement
sShift+F4Step into function
fShift+F6Finish function/loop
cShift+F5Continue running
QShift+F8Stop debugging

All of these commands are documented in the R help page for browser(); you can also type help at the Browse[N]> prompt to see them.

Special circumstances

Most of the time you’ll likely be debugging in straightforward, free-standing R functions and scripts. However, some special circumstances arise when debugging R code that’s part of a larger project; here are four that require some special mention:

Debugging outside functions

You might have noticed earlier that RStudio (and R itself, via setBreakpoint()) creates breakpoints by modifying the function in which a breakpoint is set. What happens when you set a breakpoint outside a function?

The most common use case here is halting during execution of a source() command, to examine the state during execution of an R script. R’s built-in source() command doesn’t have a way to do this, but RStudio includes its own version of source() called debugSource() that does. This version is able to halt at the breakpoints RStudio knows about.

Consequently, if a file contains breakpoints outside functions, you’ll need to call debugSource() in place of source() on that file. RStudio does this for you automatically when the file contains breakpoints and you use the RStudio Source command to source your script.

It’s important to note that debugSource is not recursive. This implies that if you call source("file1.R") inside file2.R, then execute the whole thing with debugSource("file2.R"), you’ll hit breakpoints in file2.R, but not file1.R. We generally recommend that you isolate code for debugging, but if you need to work this way, you can call debugSource manually inside your R script.

Debugging in packages

Breakpoints can be set in package code just as they can in free-standing R code. The primary difference is that you’ll need to have an up-to-date build of your package in order to set breakpoints. If your package build isn’t up to date, RStudio will warn you when you try to set a breakpoint.

In order to debug effectively in your package, you’ll also want to ensure that your package is compiled with the --with-keep.source option. This option is the default for new packages in RStudio; if you need to set it manually, it can be found in Tools -> Project Options -> Build Tools.

When a breakpoint is set in a file inside a package, RStudio will automatically disable the breakpoint when the package is unloaded and enable the breakpoint when the package is loaded. If you’re having trouble setting breakpoints in a package, make sure that the package was compiled with source information as described above and that its build is up-to-date.

Debugging in Shiny applications

Shiny applications present some challenges for the debugger because the breakpoints can’t be set until the application is executed; the function objects that need to have breakpoints injected don’t exist until then.

For this reason, breakpoints in Shiny applications only work inside the shinyServerfunction. Breakpoints are not currently supported in the user interface (i.e. ui.R), globals (i.e. global.R), or other .R sources used in Shiny applcations. This may be improved in a future version of RStudio.

Finally, be aware that Shiny’s infrastructure will show up in the callstack, and there’s quite a lot of it before control reaches your code!

Debugging in R Markdown documents

Breakpoints don’t currently work inside R chunks in R Markdown documents, so you’ll need to use browser() to halt execution in a chunk if needed.

By default, RStudio renders R Markdown documents using a separate R process when you click the Knit button. This has many benefits; it keeps the document reproducible by isolating it from your current session’s state, and it keeps the UI and console responsive while the document renders. However, debugging only works with the primary R process, so when rendering the document for debugging, you’ll need to ensure it renders there.

To do this, call rmarkdown::render() directly on your file:

> rmarkdown::render("~/mydocs/doc.Rmd") 

Finally, because R Markdown chunks don’t contain source references, most of the debugger’s visual features are disabled; you won’t see the active line highlighting in the editor and most debugging will need to be done in the console.

Further Reading

Introduction to Debugging in R (video, about 11 minutes)

R function documentation: browser(), debug(), debugonce(), options(error = …), recover(), setBreakpoint(), traceback().

Debugging, condition handling, and defensive programming by Hadley Wickham

Source References (R Journal article), by Duncan Murdoch



转载自:https://support.rstudio.com/hc/en-us/articles/205612627-Debugging-with-RStudio


更多参考:1.http://blog.youkuaiyun.com/u013259893/article/details/41254177

              2.http://blog.youkuaiyun.com/jameshadoop/article/details/26176447

确定要放弃本次机会?
福利倒计时
: :

立减 ¥

普通VIP年卡可用
立即使用
banlucainiao
关注 关注
  • 0
    点赞
  • 踩
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
  • 分享
    复制链接
    分享到 QQ
    分享到新浪微博
    扫一扫
  • 举报
    举报
专栏目录
如何在Rstudio中debug
u010945141的博客
06-12 9316
        本人不是R的重度使用者,作为菜鸟记录一下使用Rstudio的使用感想。      我的使用场景主要是生成数据建模报告。R notebook支持Markdown,而且保存成html格式可以保留图表的交互性,代码写完了,报告也完成了,不需要再转移到PPT或者在Word里面纠结贴图和表格的格式。这一点是我离不开R notebook的原因。        不过在刚接触R的时候很纠结的一点是...
使用RStudio调试(debug)基础学习(一)
weixin_30279671的博客
01-26 1395
点击行号的左侧,即可设置断点(或者按下Shift+F9),如果没有出现,反而出现下图的警告:那么只是因为我的坏习惯——写一段脚本测试的时候都是新建,但不save到本地,不喜欢保存,写的差不多了才开始取名字保存....写一个for循环测试下:test <- 0for(i in 1:9){ j <- i+2 test[i+1] <- test[i]+3 k <- i}将envi...
参与评论 您还未登录,请先 登录 后发表或查看评论
RStudio 调试
u010844092的专栏
10-21 1385
https://support.rstudio.com/hc/en-us/articles/205612627-Debugging-with-RStudio
Debugging with RStudio
lcj_cjfykx的专栏
05-30 3011
Overview RStudio includes a visual debugger that can help you understand code and find bugs. The debugger includes the following features: Editor breakpoints, both inside and outside functionsCo
【译文】使用Rstudio调试代码(debug)
leolotus的博客
08-27 7547
作者 Jonathan McPherson译者 钱亦欣 引言在R语言中dubug是个广泛讨论的话题,本文将聚焦于Rstudio内集成的debug工具。如果你想了解更多这个领域的内容,请参考下面这篇Hadley Wickham的文章。 Debugging, condition handling, and defensive programming大体上说,debug是被设计开帮助你发现代码中的问
Rstudio 显示代码行数
09-10
你可以方便地查看和调试代码,也可以更好地定位错误。 需要注意的是,以上步骤适用于Rstudio的桌面版本。如果你使用的是Rstudio的Web版本或者其他版本,具体操作步骤可能会有所不同,但是一般都会有类似的选项来...
Rstudio自定义主题
01-20
它提供了丰富的功能,包括代码编辑、调试、项目管理以及可视化等。而自定义主题则可以让用户按照个人喜好调整Rstudio的界面风格,使其更加符合个人的工作习惯。本篇文章将详细探讨如何在Rstudio中自定义主题,特别是...
Rstudio书写的R语言源代码_Rstudio.zip
09-22
Rstudio是R语言的一个集成开发环境(IDE),它提供了一个更加用户友好的界面,让程序员可以方便地编写、调试和运行R代码。Rstudio界面通常包含多个面板,分别用于源代码编辑、数据视图、命令行操作以及绘图输出等。 ...
RStudio
03-19
4. **调试工具**:RStudio提供了强大的调试功能,包括断点设置、步进执行、查看调用栈等,帮助开发者定位和修复代码问题。 5. **图形窗口**:在RStudio中,用户可以直接生成和查看各种统计图形,支持交互式调整,如...
Rstudio输入代码RUN后为什么没有任何输出?
最新发布
07-15
如果有,根据错误信息调试代码。 4. 检查RStudio设置:查看“Tools”->“Global Options”->“Console”中的设置,确保“Show output”相关选项已启用。 5. 在R Markdown中,检查代码块选项:确保没有设置`results...
RStudio:示例
02-14
RStudio 例子
通过RStudio实现Debug的操作方式
a11113112的博客
03-24 4330
R语言
Rstudio Debug 调试
wangtienhao的博客
12-26 470
RStudio 断点调试
【高手局】怎么在Rstudio中debug
为生信助力
04-24 1932
R生态很吸引人的一点是其有非常多的R包可以使用,但是有时候我们使用这些R包的函数的时候,其磨磨蹭蹭半天不出结果,有时候真的很想钻进函数里面看下代码们到底在干什么。那么有方法可以钻进函数里面一探究竟吗,有的兄弟有的,这就是debug技术。debug技术是我们进阶的必备基础技能,这个技能也是通用的技能,可以横向拓展到其它编程语言。下面我们一起学习一下如何在Rstudio中debug。
rstudio中logit模型代码
weixin_42613360的博客
01-08 496
在 RStudio 中使用逻辑回归(logit 模型)的代码示例如下: # 首先需要加载相应的包 library(glm) # 假设我们有一个数据框 df,其中包含了自变量和因变量 # 建立逻辑回归模型 logit_model <- glm(formula = 因变量 ~ 自变量, family = binomial(link = "logit"), data = df) # 打印模型结...
Rstudio的断点调试
辉的博客
04-07 5338
在代码中写入browser()的位置,程序就会在这里暂停 可以参考:https://blog.youkuaiyun.com/jameshadoop/article/details/26176447
RStudio的代码自动完成功能、键盘快捷键和代码折叠
DAT|R科学与人工智能
10-07 1429
RStudio的代码自动完成功能允许开发者在编写代码时自动完成函数名称、对象名和代码片段。当你开始输入代码时,RStudio会实时提供匹配的选项,这不仅可以节省输入时间,还能减少输入错误的概率。该功能通过提供上下文相关的建议,帮助用户快速找到并插入正确的代码片段。
使用RStudio编辑R语言代码
2301_79326891的博客
08-19 2259
本文介绍了如何使用RStudio编辑R语言代码。您可以安装R和RStudio,创建新的R脚本,并在脚本中编写和运行R代码。此外,RStudio还提供了调试工具和其他有用的功能,以提高您的编码效率。希望这篇文章对您有所帮助,祝您初学R语言语法使用RStudio编辑R语言是一种用于数据分析和统计计算的编程语言。RStudio是一个流行的集成开发环境(IDE),可以帮助您更方便地编写、调试和运行R代码。本文将介绍如何在RStudio中编辑R语言代码,并提供一些示例代码供参考。安装R和RStudio。
RStudio 断点调试 进入for循环语句调试
weixin_30883311的博客
05-18 746
参考: http://www.rstudio.com/ide/docs/debugging/overview 1.进入调试模式 全选代码,点击source即可进入调试模式。 2.进入for 调试 在For中加browser(),即可进入For语句中,在右边可以看到每个值的变化。 如: for(){ browser() } ...
banlucainiao

博客等级

码龄10年
31
原创
457
点赞
2200
收藏
317
粉丝
关注
私信

热门文章

  • numpy的ndarray与pandas的series和dataframe之间互转 89830
  • python的DataFrame排序问题 77784
  • R语言删除数据框中含有缺失值NA的行或列 73773
  • 浅谈交换机和路由器的区别 47353
  • 如何用R画折线图,散点图,平滑曲线图 46833

分类专栏

  • Spring
    7篇
  • SpringBoot
    1篇
  • 数据库
    2篇
  • 中间件
    7篇
  • 分布式和微服务
    1篇
  • C/C++
    3篇
  • Python
    81篇
  • Java
    49篇
  • Linux
    56篇
  • Statistics and R
    62篇
  • MATLAB
    17篇
  • Data Structure
  • Machine Learning & Data Mining
    33篇
  • Natural Language Processing
    7篇
  • Bioinformatics
    7篇
  • Coding
    5篇
  • Feeling
    8篇
  • Mix
    4篇
  • Scientific Research
    12篇
  • Software
    33篇
  • Database
    5篇
  • Computer  Network
    20篇
  • Maven
    2篇
  • SDN
    12篇

展开全部 收起

上一篇:
R语言不平衡数据分类指南
下一篇:
R语言Data Frame数据框常用操作

最新评论

  • Linux系统中NCBI BLAST+本地化教程

    gah0023: 好奇怪啊,我根据update_blastdb.pl nr下载了nr数据库并解压,文件夹里包含了nr.000.phd,nr.000.phi.....一直到nr.116.psq,但是就是没有单独命名为nr的文件,那我该怎么用这个指令呢?我使用blastdbcmd -info -db nr_database/nr 就会出现BLAST Database error: No alias or index file found for nucleotide database [nr_database/nr] in search path [/home/guanaohan/ncbi_db::]

  • 一个用matlab取正整数的各个位的数字的简单方法

    CCC16501650: 这种方法只有当数字小的时候才有用,数字的时候尾数是乱的如何取?

  • Spring AOP 实例解析(InvocationHandler 的invoke的proxy 参数作用)

    weixin_46604450: 还有第一个参数proxy是为了连续调用的话,为什么不设为可选参数呢?

  • Spring AOP 实例解析(InvocationHandler 的invoke的proxy 参数作用)

    weixin_46604450: 第二个参数method不是可以通过调用处理器的构造函数传入的被代理对象获得吗?为什么需要第一个参数proxy获得呢?

  • 自然语言处理中的N-Gram模型详解

    mmdxs: 里边有的图形为什么不显示表情包

最新文章

  • Excel中实现省市县乡四级联动
  • 过滤器、拦截器和AOP的分析与对比
  • Spring 官方文档(中文翻译)
2024年1篇
2023年2篇
2022年21篇
2021年4篇
2019年17篇
2018年85篇
2017年209篇
2016年38篇

目录

展开全部

收起

相关专栏

R语言

专栏

17 人学习

R语言

R语言

专栏

11 人学习

分享R语言的入门知识

用R探索医药数据科学

专栏

50 人学习

欢迎来到《用 R 语言探索医药数据科学》专栏!在这个专栏中,我们将引领你踏入医药数据科学的奇妙世界。在这里,你将深入了解如何运用强大的 R 语言工具,对医药数据进行高效处理、精准分析以及生动可视化。本专栏内容丰富全面,涵盖从基础层面到高级阶段的各类知识与技能。

目录

展开全部

收起

上一篇:
R语言不平衡数据分类指南
下一篇:
R语言Data Frame数据框常用操作

分类专栏

  • Spring
    7篇
  • SpringBoot
    1篇
  • 数据库
    2篇
  • 中间件
    7篇
  • 分布式和微服务
    1篇
  • C/C++
    3篇
  • Python
    81篇
  • Java
    49篇
  • Linux
    56篇
  • Statistics and R
    62篇
  • MATLAB
    17篇
  • Data Structure
  • Machine Learning & Data Mining
    33篇
  • Natural Language Processing
    7篇
  • Bioinformatics
    7篇
  • Coding
    5篇
  • Feeling
    8篇
  • Mix
    4篇
  • Scientific Research
    12篇
  • Software
    33篇
  • Database
    5篇
  • Computer  Network
    20篇
  • Maven
    2篇
  • SDN
    12篇

展开全部 收起

目录

评论
被折叠的  条评论 为什么被折叠? 到【灌水乐园】发言
查看更多评论
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值