Skip to content

Instantly share code, notes, and snippets.

@mwfrost
Created August 31, 2011 01:33
Show Gist options
  • Select an option

  • Save mwfrost/1182605 to your computer and use it in GitHub Desktop.

Select an option

Save mwfrost/1182605 to your computer and use it in GitHub Desktop.
pctchange <- function(v) {
# Incremental percent change
(v - c(v[1],v[-(length(v))])) / c(v[1],v[-(length(v))])
}
# weighted harmonic mean
whmean <- function(v, w){ #, na.rm=FALSE){
#v <- ifelse(na.rm==TRUE, v[!is.na(v)],v )
#w <- ifelse(na.rm==TRUE, w[!is.na(w)],w )
sum(as.numeric(w))/sum(as.numeric(w)/as.numeric(v))
}
#weighted mean
wmean <- function(v, w) { #, na.rm=FALSE){
#v <- ifelse(na.rm==TRUE, v[!is.na(v)],v )
#w <- ifelse(na.rm==TRUE, w[!is.na(w)],w )
sum(as.numeric(w)*as.numeric(v))/sum(as.numeric(w))
}
# format as percentage
# syntax: >sapply(df[c(...list of columns...),], percentify, r=1)
percentify <- function(x, r=1, keep.zeros=FALSE, na.code=""){
ifelse (as.numeric(x) != 0 | keep.zeros==TRUE, paste( format(round ( as.numeric(x) * 100, r) , nsmall=r) , '%', sep='')
,
na.code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment