Break pipeline execution in R
with breakerofchains
Suppose you have a tidyverse-style pipeline and you want to check out an intermediate output (eg, find the input to the ggplot below).
library(tidyverse)
starwars |>
select(species, sex, height, mass) |>
group_by(species, sex) |>
summarise(
height = mean(height, na.rm = TRUE),
mass = mean(mass, na.rm = TRUE)
) |>
ggplot(aes(x = height, y = mass)) +
geom_point()The long option is to just select the code you want and run that. But it’s very fiddly, and difficult to just add or remove one line, which I find annoying when debugging.
Enter breakerofchains, which adds the ability to run a pipeline up to your cursor.
Install the package with:
# install.packages("remotes")
remotes::install_github("MilesMcBain/breakerofchains")and assign a keyboard shortcut1 - I like Ctrl+Shift+B.
Then to use, just put your cursor somewhere on the last line you want to execute and hit your shortcut - the code will be executed and the result will appear in your console.
For a bonus tip, you can combine this with shrtcts to add even more functionality, eg:
- Ctrl+Shift+V to
Viewthe dataset; - Ctrl+Shift+G to
dplyr::glimpsethe dataset; and - Ctrl+Shift+W to write the data to a temporary CSV file and open the file in Excel.
To set this up, install shrtcts:
# install.packages("remotes")
remotes::install_github("gadenbuie/shrtcts")add the following to your .shrtcts.R file, which you can edit using shrtcts::edit_shortcuts():
#' View broken chain
#'
#' A shortcut to View(df) where the cursor rests
#'
#' @interactive
#'
#' @shortcut Ctrl+Shift+V
function() {
View(breakerofchains::break_chain(print_result = FALSE, assign_result = FALSE))
}
#' Glimpse broken chain
#'
#' A shortcut to glimpse(df) where the cursor rests
#'
#' @interactive
#'
#' @shortcut Ctrl+Shift+G
function() {
dplyr::glimpse(breakerofchains::break_chain(print_result = FALSE, assign_result = FALSE))
}
#' Writetmp broken chain
#'
#' A shortcut to export dataset as temp CSV where the cursor rests
#'
#' @interactive
#'
#' @shortcut Ctrl+Shift+W
function() {
writetmp <- function (.data)
{
tmpfile <- tempfile(fileext = ".csv")
readr::write_csv(.data, tmpfile)
browseURL(tmpfile)
invisible(.data)
}
writetmp(breakerofchains::break_chain(print_result = FALSE, assign_result = FALSE))
}Finally, edit your .Rprofile2 to add:
if (interactive() && requireNamespace("shrtcts", quietly = TRUE)) {
shrtcts::add_rstudio_shortcuts(set_keyboard_shortcuts = TRUE)
}You might need to close and re-open RStudio up to two times the first time for this to work.
Enjoy your new-found productivity!