Skip to content

Instantly share code, notes, and snippets.

@dsparks
dsparks / Test.md
Created February 14, 2014 19:40
A test, which I can delete.

This is a text. but changed this feel free to delete this.

  • WHy
  • Don't
  • I Try
  • A Bulleted list?

I added this.

@dsparks
dsparks / rationalFractionApproximator.R
Created October 7, 2014 14:07
Approximate any decimal with a rational fraction
rationalFractionApproximator <- function(dec, maxDenom = 1000){
denomSeq <- 1:maxDenom
impliedNumerator <- dec * denomSeq
roundNumerator <- round(impliedNumerator)
absError <- abs(roundNumerator / denomSeq - dec)
minMinimand <- which.min(absError * denomSeq)
minDenom <- denomSeq[minMinimand]
minNumer <- roundNumerator[minMinimand]
line2 <- paste0(minNumer, " / ", minDenom, " = ", minNumer / minDenom)
@dsparks
dsparks / Completion Projector.R
Created February 9, 2011 18:34
to project the time at which a loop will be finished
Projector <- function(st, loopover, iteration){
Currently <- Sys.time()
Elapsed <- (Currently - st) * length(loopover)/which(iteration == loopover)
units(Elapsed) <- "mins"
return(st + Elapsed * 60)
}
StartTime <- Sys.time()
for(oo in c(1:50)){
print(oo)
@dsparks
dsparks / GroupRank.R
Created February 9, 2011 18:35
rank within a group, then paste back together in original order
GroupRank <- function(x, group){ unsplit(lapply(split(-x, group), rank), group) }
@dsparks
dsparks / Reorderer.R
Created February 9, 2011 18:39
convert string to factor, ordered by another variable
Reorderer <- function(tofactor, inorder){ factor(tofactor, levels = tofactor[order(inorder)]) }
@dsparks
dsparks / DropTags.R
Created February 9, 2011 18:53
remove content inside html tags from string variables
DropTags <- function(x){ gsub("<[^>]*>", " ", x) }
@dsparks
dsparks / SpaceTrim.R
Created February 9, 2011 18:41
remove leading and trailing spaces from a string
spaceTrim <- function(x){ gsub("(^ +)|( +$)", "", x) }
@dsparks
dsparks / Pad0.R
Created February 9, 2011 18:38
create string variable from numeric variable with padding 0s
Pad0 <- function(x, mx=NULL, fill=0) {
## pad numeric vars to strings of specified size
lx <- nchar(as.character(x))
mx.calc <- max(lx, na.rm=TRUE)
if (!is.null(mx)) {
if (mx<mx.calc) {
stop("number of maxchar is too small")
}
} else {
mx <- mx.calc
@dsparks
dsparks / CorrelationEllipses.R
Created February 9, 2011 19:39
correlation plots with ellipses
# Correlation ellipses
doInstall <- TRUE # Change to FALSE if you don't want packages installed.
toInstall <- c("ellipse")
if(doInstall){install.packages(toInstall, repos = "http://cran.r-project.org")}
lapply(toInstall, library, character.only = TRUE)
# Function to plot colored correlation ellipses
correlationEllipses <- function(cor){
require(ellipse)
# Illustrative use of plyr
# LOAD LIBRARIES REQUIRED
library(plyr);
library(XML)
# FIGURE OUT PATTERN OF URL FOR EACH SEASON
url.b1 = 'http://ca.sports.yahoo.com/nhl/stats/byposition?pos=C,RW,LW,D';