; PSY 1903
PSY 1903 Programming for Psychologists

Suggestion Box

Spot an error or have suggestions for improvement on these notes? Let us know!

Week 10: Debugging and Using AI Tools in Quarto

0. Getting Started: Creating a Debugging Example File

Let’s practice debugging inside a Quarto document, not a regular script.
In RStudio, go to:

  • File → New File → Quarto Document
  • Enter the title "Debugging Exercise"
  • Enter your name for the author
  • Make sure "Use visual markdown editor" is unchecked
  • Click "Create blank document"

This file will let you debug interactively while also rendering reproducible reports.
You can run individual chunks with the green arrow or render the whole document to test it from a clean environment — a great way to catch hidden dependencies.


1. Why Debugging Matters

Debugging means systematically finding and fixing errors in your code.
It’s not a sign of failure — it’s a normal part of programming. Even experienced coders spend a lot of time debugging, testing, and refining their work.

Debugging isn’t just about fixing problems. It’s about understanding what your code is doing and ensuring that it behaves as intended.
In Quarto, debugging is also a crucial part of reproducibility — because rendering always runs in a fresh R session, you’ll quickly find code that depends on objects not defined inside your document.

Tip: If a chunk fails when you render, that’s actually helpful — it means your code isn’t relying on something in your global environment, which keeps your analysis reproducible.


2. Reading and Interpreting Errors in Quarto

When a chunk fails, Quarto displays an error in the Render pane or inline in your document.
The key is to read the message carefully — R often tells you exactly what went wrong.

Example 1: Object not found

```{r}
## Example 1: Object not found
mean(rt)
## Error in mean(rt) : object 'rt' not found
```

R can’t find rt because it wasn’t defined.
Use ls() to see which objects exist in your Quarto session:

```{r}
ls()
```

Example 2: Missing Parenthesis

```{r}
## Example 2: Missing Parenthesis
print("Hello"
## Error: unexpected end of input
```

This means R hit the end of the line without finding a closing parenthesis or quote — one of the most common syntax mistakes.


Example 3: NA Propagation

```{r}
## Example 3: NA Propagation
mean(c(1, 2, NA))
## [1] NA
```

By default, R includes missing values (NA) in calculations.
Add na.rm = TRUE to ignore them:

```{r}
mean(c(1, 2, NA), na.rm = TRUE)
```

Example 4: Wrong Data Type

```{r}
## Example 4: Wrong Data Type
mean(c("a", "b", "c"))
## Error in mean(c("a", "b", "c")) : 'x' must be numeric
```

Always check the structure of your variables:

```{r}
str(c("a", "b", "c"))
```

Common Error Types and Tools

Error Type Common Cause Helpful Tools
Syntax error Missing parentheses or quotes Check structure, use RStudio’s auto-indent (Cmd/Ctrl + I)
Object not found Variable not defined or cleared ls(), str(), traceback()
NA propagation Missing values not handled summary(), is.na(), na.rm = TRUE
Wrong data type Text instead of numeric str(), as.numeric()
Unexpected output Logic or indexing error print(), browser(), traceback()

3. Debugging Tools in Quarto

Each of these works inside Quarto just like in a script.
You can add them inside a chunk, re-run the chunk, and inspect the output inline or in the console.

Tool What It Does When to Use It
print() Shows intermediate values Track variables during execution
str() Displays structure and type When output looks strange
traceback() Shows sequence of function calls Immediately after an error
browser() Pauses inside a function for inspection Debug step-by-step inside your code
recover() Lets you explore error environments For nested function debugging
stop() / warning() Creates intentional errors or warnings For testing or validation

Example: Using traceback() and browser() in Quarto

```{r}
## Example: Using `traceback()` and `browser()` in Quarto

calculate_mean_rt <- function(data) {
  mean(rt, na.rm = TRUE)
}
calculate_mean_rt(experiment_data)
```

When this fails:

Error in mean(rt, na.rm = TRUE) : object 'rt' not found

You can inspect with:

```{r}
traceback()
```

Then modify the function:

```{r}
calculate_mean_rt <- function(data) {
  browser()   # pauses execution
  mean(rt, na.rm = TRUE)
}
calculate_mean_rt(experiment_data)
```

When Quarto pauses, the Console opens in interactive debug mode.
Type ls() to see what’s in scope — you’ll notice rt isn’t there.
The correct call should be mean(data$rt, na.rm = TRUE).


4. A Systematic Debugging Workflow (for Quarto)

You can follow the same systematic process inside a .qmd:

  1. Reproduce the error. Run or render again to confirm.
  2. Read the message. Check the chunk output for where it fails.
  3. Simplify the problem. Try a smaller code snippet in a new chunk.
  4. Inspect objects. Use ls(), str(), and head() inside the chunk.
  5. Add prints. Use print() or cat() to trace logic.
  6. Test from a clean render. Render again — Quarto clears the environment each time.
  7. Document your fix. Leave a short comment for future reference.

Quarto’s clean render makes it the perfect debugging environment — it automatically simulates a “fresh start” every time.


5. Using AI Tools for Debugging and Refactoring

AI tools like ChatGPT can help you interpret errors and clarify confusing behavior.
They’re especially good at explaining unfamiliar error messages or refactoring code into a cleaner, more vectorized style.

Good prompts:

“I’m trying to calculate the mean of a column called rt inside a function, but R says object 'rt' not found. Here’s my code chunk — can you explain why?”

“Why does this Quarto chunk fail when rendering but not when I run it interactively?”

“Can you rewrite this loop using vectorized functions like ifelse()?”


6. Integrating AI into Your Workflow

AI should be a collaborator, not a shortcut. Use it to understand, not to outsource thinking.

Best Practices:

  • Always verify AI’s code by running it in your .qmd.
  • Ask why something works, not just what to change.
  • Provide clear context and sample data in your prompt.
  • Test AI suggestions on a subset before trusting results.

7. Summary

  • Debugging helps you understand what your code is actually doing.
  • In Quarto, rendering from a clean session helps expose hidden dependencies.
  • Use print(), traceback(), and browser() to locate and diagnose problems.
  • Follow a structured workflow and document your fixes.
  • Use AI to help explain and refactor code — but always double-check.

See also: Best Practices Notes, Scope Notes, and Troubleshooting Loops & Functions.