R调试时如何快速打印当前所有变量的取值?
recover() Debugger Great question! When you’ve set options(error=recover) and landed in the debugger after an error, navigating to a frame (like entering 1 for the top-level environment) and wanting to see all local variables’ values doesn’t have to be a tedious ls() + manual check process. Here are a few straightforward methods:
Use
ls.str()
This is the simplest built-in solution. Just typels.str()in the debugger prompt, and it will list every object in the current environment alongside its structure and current value. It’s concise and gives you a clear overview of all local variables at once.Use
mget()+print()
If you prefer the output as a named list (which can be easier to scan for specific variables), run:print(mget(ls()))This fetches all objects returned by
ls()and prints them in list form, with each variable name as the list key.Create a reusable helper function
If you do this debugging workflow often, add a small helper function to your.Rprofileso it’s always accessible. For example:show_all_vars <- function() { current_env <- parent.frame() print(mget(ls(envir = current_env), envir = current_env)) }Then, when you’re in the
recover()frame, just typeshow_all_vars()to get a quick printout of all local variables and their values.
One extra tip: Remember you can switch between different stack frames by entering the corresponding number in the debugger prompt—each frame has its own set of local variables, and these methods work for any frame you navigate to.
内容的提问来源于stack exchange,提问作者honeybadger

