SlideShare a Scribd company logo
Interactive Debugging with Environment Browser
Leon Kim | www.betweentwotests.com
Overview of base::browser()
This is a brief overview of base::browser() and how to use
it for debugging in R.
browser() is default function found in R.
Useful tool to “hack into” R functions (that you or other
people wrote)
Typical day in lab
head(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
Task: Researcher’s ruler was off by 5 inches. Let’s adjust it!
Oops
# Loop through each column and add 5
df <- iris
for(j in 1:ncol(df)){
df[,j] <- df[,j] + 5
}
## Warning in Ops.factor(df[, j], 5): '+' not meaningful for factors
unlist(lapply(iris, class))
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## "numeric" "numeric" "numeric" "numeric" "factor"
Forgot that Species column is not numeric!
Quick and dirty solution
# Loop through each column EXCEPT the last one
df <- iris
for(j in 1:(ncol(df)-1)){
df[,j] <- df[,j] + 5
}
head(df)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 10.1 8.5 6.4 5.2 setosa
## 2 9.9 8.0 6.4 5.2 setosa
## 3 9.7 8.2 6.3 5.2 setosa
## 4 9.6 8.1 6.5 5.2 setosa
## 5 10.0 8.6 6.4 5.2 setosa
## 6 10.4 8.9 6.7 5.4 setosa
We got lucky
Not all error messages are obvious
Not all bugs come from such easy code
Not all bugs are this easy to fix
More likely scenario
foo_1 <- function(x) { ... }
foo_2 <- function(x) { ... }
# Code that produces some error
for(j in 1:ncol(df)){
foo_1(df[,j]); foo_2(df[,j])
}
foos <- function(x) {
foo_1(foo_2(x))
}
super_foo <- function(df) {
# Code that produces some error
for(j in 1:ncol(df)){
foos(df[,j])
}
}
super_foo(iris)
browser() to the rescue
for(j in 1:ncol(df)){
browser() <--------
foo_1(df[,j])
foo_2(df[,j])
}
Example
add_five <- function(x) {x + 5}
df <- iris
outside_var <- "I'm outside the loop"
for(j in 1:ncol(df)){
print(paste("start of the iteration:", j))
inside_var <- "I'm inside the loop"
browser()
df[,j] <- add_five(df[,j])
print(paste("end of the interation:", j))
}
Trigger browser() mode
Run your code
Run expressions within browser() mode
What can I do in browser() mode?
Type help for list of avaiable commands
‘c’: execute all of the function
Executes everything left (until the next browser() call that is)
Sanity check: has the first column of df been changed?
‘n’: Go to the next line
Moves to beginning of the next line
Also executes your current line (before moving to next ine)
‘s’: R-ception
Go into the function call
In RStudio
GUI supports (for function calls)
Access everything inside the function environment
Access variables as the function sees it
Effectively use browser() : #1
add_five <- function(x) {x + 5}
df <- iris
for(j in 1:ncol(df)){
if(j == 5) {
browser()
}
df[,j] <- add_five(df[,j])
}
Effectively use browser() : #2
library(dplyr)
df <- iris
df %>%
group_by(Species) %>%
mutate(avg_sepal_length =
list(Species = Species,
Sepal.Length = Sepal.Length) %>%
browser()
)
Look at individual group
Pass data to browser()
tl;dr
browser() allows you to interactively code in any environment
scope during R execution

More Related Content

PDF
Leaks & Zombies
ODP
NUMOSS 4th Week - Commandline Tutorial
ODP
Linux Command Line
PPTX
A Prettier Printer
PDF
Pry at the Ruby Drink-up of Sophia, February 2012
ODP
Shell Scripting
PDF
Tests unitaires pour PostgreSQL avec pgTap
Leaks & Zombies
NUMOSS 4th Week - Commandline Tutorial
Linux Command Line
A Prettier Printer
Pry at the Ruby Drink-up of Sophia, February 2012
Shell Scripting
Tests unitaires pour PostgreSQL avec pgTap

What's hot (20)

PDF
Introduction functionalprogrammingjavascript
PDF
PDF
The Power of CSS
PPTX
Linux basic3
PDF
Functional Pattern Matching on Python
PDF
ch8-pv1-the-virtual-filesystem
PPTX
What is suid, sgid and sticky bit
PPS
Bdd: Tdd and beyond the infinite
PDF
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
PDF
Php radomize
PDF
Python and rust 2018 pythonkorea jihun
PPTX
What is recursion?
PPTX
Using the Power to Prove
PPTX
Down the rabbit hole, profiling in Django
PDF
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
PDF
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
RTF
PDF
Some Pry Features
Introduction functionalprogrammingjavascript
The Power of CSS
Linux basic3
Functional Pattern Matching on Python
ch8-pv1-the-virtual-filesystem
What is suid, sgid and sticky bit
Bdd: Tdd and beyond the infinite
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
Php radomize
Python and rust 2018 pythonkorea jihun
What is recursion?
Using the Power to Prove
Down the rabbit hole, profiling in Django
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Some Pry Features
Ad

Similar to Using browser() in R (20)

PDF
Exploring Clojurescript
PPTX
Kernel-Level Programming: Entering Ring Naught
KEY
Clojure Intro
PDF
Ruby - Uma Introdução
PDF
Zen and the Art of Code Maintenance
PDF
Full Stack Clojure
PDF
Coding in GO - GDG SL - NSBM
PDF
Pune Clojure Course Outline
PPTX
FParsec Hands On - F#unctional Londoners 2014
PPTX
python beginner talk slide
PDF
Clojure for Java developers - Stockholm
PDF
Python utan-stodhjul-motorsag
PDF
PythonOOP
PPTX
R Debugging
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
R Data Analysis/Rを使った人事データ分析入門
PDF
Performance Profiling in Rust
PDF
Neal Ford Emergent Design And Evolutionary Architecture
PDF
Frege - consequently functional programming for the JVM
PDF
Fantastic DSL in Python
Exploring Clojurescript
Kernel-Level Programming: Entering Ring Naught
Clojure Intro
Ruby - Uma Introdução
Zen and the Art of Code Maintenance
Full Stack Clojure
Coding in GO - GDG SL - NSBM
Pune Clojure Course Outline
FParsec Hands On - F#unctional Londoners 2014
python beginner talk slide
Clojure for Java developers - Stockholm
Python utan-stodhjul-motorsag
PythonOOP
R Debugging
ClojureScript loves React, DomCode May 26 2015
R Data Analysis/Rを使った人事データ分析入門
Performance Profiling in Rust
Neal Ford Emergent Design And Evolutionary Architecture
Frege - consequently functional programming for the JVM
Fantastic DSL in Python
Ad

Recently uploaded (20)

PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PPTX
climate analysis of Dhaka ,Banglades.pptx
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PPTX
Major-Components-ofNKJNNKNKNKNKronment.pptx
PDF
Lecture1 pattern recognition............
PPTX
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
.pdf is not working space design for the following data for the following dat...
PPTX
Global journeys: estimating international migration
PDF
Introduction to Business Data Analytics.
PPT
Reliability_Chapter_ presentation 1221.5784
PPTX
1_Introduction to advance data techniques.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PPTX
Introduction to Knowledge Engineering Part 1
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
PPTX
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
PPTX
Moving the Public Sector (Government) to a Digital Adoption
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
climate analysis of Dhaka ,Banglades.pptx
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
Major-Components-ofNKJNNKNKNKNKronment.pptx
Lecture1 pattern recognition............
05. PRACTICAL GUIDE TO MICROSOFT EXCEL.pptx
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
.pdf is not working space design for the following data for the following dat...
Global journeys: estimating international migration
Introduction to Business Data Analytics.
Reliability_Chapter_ presentation 1221.5784
1_Introduction to advance data techniques.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
Introduction to Knowledge Engineering Part 1
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
Moving the Public Sector (Government) to a Digital Adoption
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...

Using browser() in R

  • 1. Interactive Debugging with Environment Browser Leon Kim | www.betweentwotests.com
  • 2. Overview of base::browser() This is a brief overview of base::browser() and how to use it for debugging in R. browser() is default function found in R. Useful tool to “hack into” R functions (that you or other people wrote)
  • 3. Typical day in lab head(iris) ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ## 6 5.4 3.9 1.7 0.4 setosa Task: Researcher’s ruler was off by 5 inches. Let’s adjust it!
  • 4. Oops # Loop through each column and add 5 df <- iris for(j in 1:ncol(df)){ df[,j] <- df[,j] + 5 } ## Warning in Ops.factor(df[, j], 5): '+' not meaningful for factors unlist(lapply(iris, class)) ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## "numeric" "numeric" "numeric" "numeric" "factor" Forgot that Species column is not numeric!
  • 5. Quick and dirty solution # Loop through each column EXCEPT the last one df <- iris for(j in 1:(ncol(df)-1)){ df[,j] <- df[,j] + 5 } head(df) ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 10.1 8.5 6.4 5.2 setosa ## 2 9.9 8.0 6.4 5.2 setosa ## 3 9.7 8.2 6.3 5.2 setosa ## 4 9.6 8.1 6.5 5.2 setosa ## 5 10.0 8.6 6.4 5.2 setosa ## 6 10.4 8.9 6.7 5.4 setosa
  • 6. We got lucky Not all error messages are obvious Not all bugs come from such easy code Not all bugs are this easy to fix
  • 7. More likely scenario foo_1 <- function(x) { ... } foo_2 <- function(x) { ... } # Code that produces some error for(j in 1:ncol(df)){ foo_1(df[,j]); foo_2(df[,j]) } foos <- function(x) { foo_1(foo_2(x)) } super_foo <- function(df) { # Code that produces some error for(j in 1:ncol(df)){ foos(df[,j]) } } super_foo(iris)
  • 8. browser() to the rescue for(j in 1:ncol(df)){ browser() <-------- foo_1(df[,j]) foo_2(df[,j]) }
  • 9. Example add_five <- function(x) {x + 5} df <- iris outside_var <- "I'm outside the loop" for(j in 1:ncol(df)){ print(paste("start of the iteration:", j)) inside_var <- "I'm inside the loop" browser() df[,j] <- add_five(df[,j]) print(paste("end of the interation:", j)) }
  • 10. Trigger browser() mode Run your code Run expressions within browser() mode
  • 11. What can I do in browser() mode? Type help for list of avaiable commands
  • 12. ‘c’: execute all of the function Executes everything left (until the next browser() call that is) Sanity check: has the first column of df been changed?
  • 13. ‘n’: Go to the next line Moves to beginning of the next line Also executes your current line (before moving to next ine)
  • 14. ‘s’: R-ception Go into the function call
  • 15. In RStudio GUI supports (for function calls)
  • 16. Access everything inside the function environment Access variables as the function sees it
  • 17. Effectively use browser() : #1 add_five <- function(x) {x + 5} df <- iris for(j in 1:ncol(df)){ if(j == 5) { browser() } df[,j] <- add_five(df[,j]) }
  • 18. Effectively use browser() : #2 library(dplyr) df <- iris df %>% group_by(Species) %>% mutate(avg_sepal_length = list(Species = Species, Sepal.Length = Sepal.Length) %>% browser() )
  • 19. Look at individual group Pass data to browser()
  • 20. tl;dr browser() allows you to interactively code in any environment scope during R execution