Skip to content

Instantly share code, notes, and snippets.

View mxblsdl's full-sized avatar
🦊
Focusing

Max Blasdel mxblsdl

🦊
Focusing
View GitHub Profile
@mxblsdl
mxblsdl / close_connections.R
Created June 18, 2022 15:35
Example of callback function for when shiny closes
# Close connection to database when app closes
cancel.onSessionEnded <- session$onSessionEnded(function() {
if(exists("con")){
dbDisconnect(con)
print("Connection to DB Closed")
}
})
@mxblsdl
mxblsdl / jbox.R
Last active June 18, 2022 15:34
Example of using jbox with shiny
# UI
tags$script(
src = paste0(
"https://cdn.jsdelivr.net/gh/StephanWagner/",
"[email protected]/dist/jBox.all.min.js"
)
),
tags$link(
rel = "stylesheet",
@mxblsdl
mxblsdl / dual_axis.R
Created April 2, 2021 17:34
Plot two different axis in ggplot
# set the limits of each axis
# these will need to be changed for each data
# use summary(df) to get metrics
ylim_prime <- c(0.35, 0.76)
ylim_sec <- c(6200, 12000)
# calculate values for use in plot
b <- diff(ylim_prime)/diff(ylim_sec)
a <- ylim_prime[1] - b*ylim_sec[1]
switch (
menu(choices = c("base", "mid", "DC"), graphics = T, title = "DC Charging Scenario"),
"base",
"mid",
"DC"
)
@mxblsdl
mxblsdl / git prompt
Created September 12, 2020 21:03
set your prompt to display the current git branch. Should be added to the .Rprofile file
if(requireNamespace("prompt", quietly = T)) {
prompt_git <- function(...) {
paste0(
"[", prompt::prompt_git(), "]", "> "
)
}
prompt::set_prompt(prompt_git)
rm(prompt_git)
}
@mxblsdl
mxblsdl / console git
Created August 3, 2020 21:56
Set the prompt to show the current git branch
options(prompt = glue::glue("[git] {crayon::bgRed(crayon::white(as.character(git2r::repository_head())[1]))} >"))
@mxblsdl
mxblsdl / markdown root dir
Created August 1, 2020 20:43
Set the working directory of an R markdown to that of the project file
# For R projects
knitr::opts_knit$set(root.dir = rprojroot::find_rstudio_root_file())
# add fake columns
cols_add <- as.character(2020:2039)
DT[, (cols_add) := 0]
for (col in cols_add) {
set(DT, i = 1L, j = col, value = state[1, total] * abs(rnorm(1, mean = 10)) + state[1, total])
set(DT, i = 2L, j = col, value = state[2, total] * abs(rnorm(1)) + state[2, total])
set(DT, i = 3L, j = col, value = state[3, total] * abs(rnorm(1)) + state[3, total])
@mxblsdl
mxblsdl / list shapefiles
Created July 6, 2020 23:46
Find shapefiles in a single folder. Ignores all the other shapefile files
list.shp <- function(path) {
list.files(path, pattern = ".shp$", full.names = T)
}
cat(paste0("export(", gsub(".R$", "", list.files("R")), ")"), sep = "\n")