Skip to content

Instantly share code, notes, and snippets.

@seasmith
seasmith / compound-interest.R
Last active February 22, 2020 18:14
Financials
library(purrr)
# Other ideas: https://stackoverflow.com/questions/21335947/compound-interest-calculation-on-changing-balance-for-data-table
compound_interest <- function(principle, interest, periods = NULL, haircut = NULL) {
if (is.null(periods)) {
nseq <- length(interest)
} else {
nseq <- periods
interest <- rep(interest, nseq)
@seasmith
seasmith / lighten-by.R
Created February 21, 2020 03:25
Lighten colors by group
library(tidyverse)
library(colorspace)
lighten_by <- function (x, ..., group_colors = c("red", "blue"), adjust = 0.9) {
color_groups <- enquos(...)
split_x <- x %>%
arrange(!!color_groups[[1]]) %>%
split(x[, quo_name(color_groups[[1]])])
@seasmith
seasmith / 2d-density.R
Last active September 11, 2019 14:21
2D-density
# From ggpoindensity
count_neighbors_r <- function(x, y, r2, xy) {
yx <- 1 / xy
sapply(1:length(x), function(i) {
sum((yx * (x[i] - x) ^ 2) + (xy * (y[i] - y) ^ 2) < r2)
})
}
# Others:
# * dbscan::pointdensity
@seasmith
seasmith / iris-lm.R
Created July 21, 2019 03:51
Modeling with the iris data set
library(broom) # alt to par(mfrow(2,2)); plot(mod)
library(rsample)
library(dplyr)
library(ggplot2) # alt to par(mfrow(2,2)); plot(mod)
set.seed(1492)
ifrac <- initial_split(iris)
iris_test <- testing(ifrac)
iris_trian <- training(ifrac)
# From ?image and expanded upon
pat_circles <- function (n = 27) {
x <- seq(-4*pi, 4*pi, length.out = n)
sqrt(outer(x^2, x^2, "+"))
}
eq1 <- function (x) {
cos(x^2) * exp(-x/6)
}
@seasmith
seasmith / invert-color.R
Last active July 20, 2019 21:34
Inverting color maps
library(pals)
library(purrr) # in this order
library(ggplot2)
library(colorspace)
library(magrittr)
# Invert color
invert_color <- function (pal, n = 256) {
rgb_mat <- colorspace::hex2RGB(pal(n))
@seasmith
seasmith / keyword-vector-subsetting.R
Created July 18, 2019 16:44
Intuitive vector subsetting using keywords
`[.hmmm` <- function (x, i, ...) {
isub <- substitute(i)
is_seq <- identical(as.list(isub)[[1L]], as.name(":"))
if (is_seq) {
end_seq <- as.list(isub)[[3L]]
is_end <- identical(end_seq, as.name("end"))
@seasmith
seasmith / lazylist.R
Created July 17, 2019 03:10
Evaluate a list lazily
# Taken from: https://twitter.com/dirk_sch/status/1151080975952228352
"[[.ll" <- function(x, i) {
rlang::eval_tidy(x$call_list[[i]])
}
lazylist <- function(...) {
calls <- rlang::enexprs(...)
structure(list(call_list = calls), class = "ll")
}
@seasmith
seasmith / uncovering-the-tidyeval-quosure.R
Created July 7, 2019 01:33
Examination of tidyeval's quosure
library(rlang)
# Underneath the hood of a quosure ------------------------------------
v <- "a variable"
vquo <- quo(v)
print(vquo)
#> <quosure>
#> expr: ^v