Skip to content

Instantly share code, notes, and snippets.

@dsparks
dsparks / CoefficientPlot.R
Last active November 29, 2017 22:36
ggplot2 coefficient plot, with discrete interval bounds
CoefficientPlot <- function(models, alpha = 0.05, modelnames = ""){
# models must be a list()
Multiplier <- qnorm(1 - alpha / 2)
CoefficientTables <- lapply(models, function(x){summary(x)$coef})
TableRows <- unlist(lapply(CoefficientTables, nrow))
if(modelnames[1] == ""){
ModelNameLabels <- rep(paste("Model", 1:length(TableRows)), TableRows)
} else {
@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 / LineFinder.R
Created February 9, 2011 18:36
locates a string in a vector of strings
lineFinder <- function(string, vector){ (1:length(vector))[regexpr(string, vector) != -1] }
@dsparks
dsparks / MakeTable.R
Created February 9, 2011 18:37
helper function for parsing text
makeTable <- function(vector, toregex){ do.call(rbind, strsplit(vector, toregex)) }
@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 / 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 / SmoothCoefficientPlot.R
Last active April 5, 2022 19:32
ggplot2 regression coefficient plot, intervals smoothed out to transparent
SmoothCoefficientPlot <- function(models, modelnames = "", removeintercept = FALSE){
# models must be a list()
Alphas <- seq(1, 99, 2) / 100
Multiplier <- qnorm(1 - Alphas / 2)
zzTransparency <<- 1/(length(Multiplier)/4)
CoefficientTables <- lapply(models, function(x){summary(x)$coef})
TableRows <- unlist(lapply(CoefficientTables, nrow))
@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 / DropTags.R
Created February 9, 2011 18:53
remove content inside html tags from string variables
DropTags <- function(x){ gsub("<[^>]*>", " ", x) }