#' Refresh R Shell
#'
#' This function effectively generates a new R shell. It clears the global environment, detaches any packages and clears the console. Probably most useful when testing a script as if it were in a fresh shell.
#' @param keep A vector of CASE-SENSITIVE object names that you wish to be spared from the mighty axe of refresh().
#' @keywords refresh clear
#' @export
#' @examples
#' ## Not run ##
#' refresh()
#' @import magrittr
refresh <- function(keep = NULL) {
startup <-
c('.GlobalEnv', 'tools:rstudio', 'package:stats', 'package:graphics', 'package:grDevices', 'package:utils',
'package:datasets', 'package:methods', 'Autoloads', 'package:base', 'package:Dantools', 'package:magrittr',
'package:tidyverse', 'package:ggplot2', 'package:tibble', 'package:tidyr', 'package:readr', 'package:purrr',
'package:dplyr', 'package:stringr', 'package:forcats')
# Vector of packages etc. to keep.
search()[!search() %in% startup] %T>%
{ options(warn = -1) } %>%
lapply(FUN = detach, character.only = TRUE, unload = TRUE) %T>%
{ options(warn = 0) } %>%
invisible
# Detach everything not in 'startup'.
if ( !is.null(keep) ) {
# If no an object has been passed to 'keep', make sure it isn't removed.
keep %<>%
lapply(FUN = function(k) {
grep(pattern = paste0('^', k, '$'),
x = ls(envir = as.environment('.GlobalEnv')),
ignore.case = FALSE) }) %>%
unlist %>%
{ rm(list = ls(name = '.GlobalEnv')[-.],
envir = as.environment('.GlobalEnv')) }
} else {
# If nothing has been given to 'keep', remove everything.
rm(list = ls(name = '.GlobalEnv'),
envir = as.environment('.GlobalEnv'))
}
while ( !is.null(dev.list()) ) { dev.off() }
# Unload graphics devices until they're all gone.
cat("\014")
# Clear the prompt.
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.