Skip to content

Instantly share code, notes, and snippets.

View mikmart's full-sized avatar

Mikko Marttila mikmart

  • Orion Pharma
  • United Kingdom
View GitHub Profile
@mikmart
mikmart / substitute-stack.md
Last active July 20, 2018 08:49
Substitute expression in the call stack
# Substitute a bare expression in all call stack envs
substitute_stack <- function(expr) {
  substitute_stack_q(substitute(expr))
}

# Substitute a quoted expression in all call stack envs
substitute_stack_q <- function(expr) {
  envs <- sys.frames() # call stack
 for (e in rev(envs)) {
@mikmart
mikmart / reverse-time.md
Last active September 30, 2024 21:33
Reversing a time axis in ggplot2

An answer to this closed StackOverflow question about reversing a time axis in ggplot2.

date = c("2011-11-15", "2011-11-16", "2011-11-17", "2011-11-19")
start = c("12:01:27", "12:01:25", "12:01:02", "12:01:12")
end = c("12:30:15", "12:32:15", "12:39:12", "12:30:18")

df = data.frame(date = as.POSIXct(date),
     ystart = as.POSIXct(start, format="%H:%M:%S"), 
     yend = as.POSIXct(end, format="%H:%M:%S"),
@mikmart
mikmart / applying-arrays.R
Last active March 10, 2018 21:13
Calculating summaries from arrays without loops
set.seed(1)
n <- 1000
matrices <- replicate(n, matrix(runif(24 ^ 2), nrow = 24))
str(matrices)
#> num [1:24, 1:24, 1:1000] 0.266 0.372 0.573 0.908 0.202 ...
f <- function(x) {
sum_x <- sum(x)
if (sum_x == 0)
@mikmart
mikmart / complete_count.R
Last active February 19, 2018 10:28
Counting and completing, with special behaviour for `grouped_df`
library(tidyverse)
library(rlang)
complete_count <- function(.data, ...) {
UseMethod("complete_count")
}
complete_count.grouped_df <- function(.data, ...) {
grps <- groups(.data)
@mikmart
mikmart / ols.py
Created January 19, 2016 17:08
Simple OLS with Python
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
Simple OLS with Python
Fitting a simple OLS regression model using linear algebra with Python,
following the first Matlab programming excercise for Machine Learning.
Author: