SlideShare a Scribd company logo
1 of 20
Download to read offline
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

What's hot

Introduction functionalprogrammingjavascript
Introduction functionalprogrammingjavascriptIntroduction functionalprogrammingjavascript
Introduction functionalprogrammingjavascriptCarolina Pascale Campos
 
The Power of CSS
The Power of CSSThe Power of CSS
The Power of CSSAniket Pant
 
Functional Pattern Matching on Python
Functional Pattern Matching on PythonFunctional Pattern Matching on Python
Functional Pattern Matching on PythonDaker Fernandes
 
ch8-pv1-the-virtual-filesystem
ch8-pv1-the-virtual-filesystemch8-pv1-the-virtual-filesystem
ch8-pv1-the-virtual-filesystemyushiang fu
 
What is suid, sgid and sticky bit
What is suid, sgid and sticky bit  What is suid, sgid and sticky bit
What is suid, sgid and sticky bit Meenu Chopra
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteGiordano Scalzo
 
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
   מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה    מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה
מודלים חישוביים - תרגול מס 2 - אוניברסיטת חיפה Igor Kleiner
 
Php radomize
Php radomizePhp radomize
Php radomizedo_aki
 
Python and rust 2018 pythonkorea jihun
Python and rust 2018 pythonkorea jihunPython and rust 2018 pythonkorea jihun
Python and rust 2018 pythonkorea jihunJIHUN KIM
 
Using the Power to Prove
Using the Power to ProveUsing the Power to Prove
Using the Power to ProveKazuho Oku
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoRemco Wendt
 
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbСтажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonb
Стажировка 2016-07-27 02 Денис Нелюбин. PostgreSQL и jsonbSmartTools
 
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataKernel Recipes 2019 - GNU poke, an extensible editor for structured binary data
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataAnne Nicolas
 
Some Pry Features
Some Pry FeaturesSome Pry Features
Some Pry FeaturesYann VERY
 

What's hot (20)

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

Similar to Using browser() in R

Exploring Clojurescript
Exploring ClojurescriptExploring Clojurescript
Exploring ClojurescriptLuke Donnet
 
Kernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring NaughtKernel-Level Programming: Entering Ring Naught
Kernel-Level Programming: Entering Ring NaughtDavid Evans
 
Clojure Intro
Clojure IntroClojure Intro
Clojure Introthnetos
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma IntroduçãoÍgor Bonadio
 
Zen and the Art of Code Maintenance
Zen and the Art of Code MaintenanceZen and the Art of Code Maintenance
Zen and the Art of Code MaintenanceJemuel Young
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
FParsec Hands On - F#unctional Londoners 2014
FParsec Hands On -  F#unctional Londoners 2014FParsec Hands On -  F#unctional Londoners 2014
FParsec Hands On - F#unctional Londoners 2014Phillip Trelford
 
python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
Clojure for Java developers - Stockholm
Clojure for Java developers - StockholmClojure for Java developers - Stockholm
Clojure for Java developers - StockholmJan Kronquist
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門Takanori Omote
 
Performance Profiling in Rust
Performance Profiling in RustPerformance Profiling in Rust
Performance Profiling in RustInfluxData
 
Neal Ford Emergent Design And Evolutionary Architecture
Neal Ford Emergent Design And Evolutionary ArchitectureNeal Ford Emergent Design And Evolutionary Architecture
Neal Ford Emergent Design And Evolutionary ArchitectureThoughtworks
 
Frege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMFrege - consequently functional programming for the JVM
Frege - consequently functional programming for the JVMDierk König
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Pythonkwatch
 

Similar to Using browser() in R (20)

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

Recently uploaded

Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSAishani27
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFxolyaivanovalion
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfMarinCaroMartnezBerg
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxolyaivanovalion
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Delhi Call girls
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAroojKhan71
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiSuhani Kapoor
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingNeil Barnes
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023ymrp368
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改atducpo
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...Suhani Kapoor
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxolyaivanovalion
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...Suhani Kapoor
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxStephen266013
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 

Recently uploaded (20)

Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
Ukraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICSUkraine War presentation: KNOW THE BASICS
Ukraine War presentation: KNOW THE BASICS
 
Halmar dropshipping via API with DroFx
Halmar  dropshipping  via API with DroFxHalmar  dropshipping  via API with DroFx
Halmar dropshipping via API with DroFx
 
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
꧁❤ Aerocity Call Girls Service Aerocity Delhi ❤꧂ 9999965857 ☎️ Hard And Sexy ...
 
FESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdfFESE Capital Markets Fact Sheet 2024 Q1.pdf
FESE Capital Markets Fact Sheet 2024 Q1.pdf
 
Edukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFxEdukaciniai dropshipping via API with DroFx
Edukaciniai dropshipping via API with DroFx
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al BarshaAl Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
Al Barsha Escorts $#$ O565212860 $#$ Escort Service In Al Barsha
 
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service BhilaiLow Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
Low Rate Call Girls Bhilai Anika 8250192130 Independent Escort Service Bhilai
 
Brighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data StorytellingBrighton SEO | April 2024 | Data Storytelling
Brighton SEO | April 2024 | Data Storytelling
 
Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
Data-Analysis for Chicago Crime Data 2023
Data-Analysis for Chicago Crime Data  2023Data-Analysis for Chicago Crime Data  2023
Data-Analysis for Chicago Crime Data 2023
 
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
代办国外大学文凭《原版美国UCLA文凭证书》加州大学洛杉矶分校毕业证制作成绩单修改
 
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
VIP High Profile Call Girls Amravati Aarushi 8250192130 Independent Escort Se...
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
Smarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptxSmarteg dropshipping via API with DroFx.pptx
Smarteg dropshipping via API with DroFx.pptx
 
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
VIP High Class Call Girls Jamshedpur Anushka 8250192130 Independent Escort Se...
 
B2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docxB2 Creative Industry Response Evaluation.docx
B2 Creative Industry Response Evaluation.docx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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