Skip to content

Instantly share code, notes, and snippets.

@cdiener
Created May 4, 2016 19:47
Show Gist options
  • Save cdiener/5817d32e5411e14dcd2cb9d2ce6da630 to your computer and use it in GitHub Desktop.
Save cdiener/5817d32e5411e14dcd2cb9d2ce6da630 to your computer and use it in GitHub Desktop.
Small GSEA implementation
ES <- function(p, w, pws, both=FALSE) {
n <- length(pws)
nr <- sum(abs(w[pws == p]))
nh <- sum(pws == p)
scores <- vector(length=n)
scores[pws == p] <- abs(w[pws == p])/nr
scores[pws != p] <- -1/(n - nh)
r <- range(cumsum(scores))
i <- which.max(abs(r))
if (both) i <- 1:2
r[i]
}
NES <- function(p, w, pws, n=200) {
es <- ES(p, w, pws)
norm <- replicate(n, ES(p, w, sample(pws), both=TRUE))
if (es < 0) {
no <- norm[norm < 0]
nes <- -es/mean(no)
pval <- sum(no < es)/length(no)
} else {
no <- norm[norm >= 0]
nes <- es/mean(no)
pval <- sum(no > es)/length(no)
}
return(c(nes, pval))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment