Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Percent of Y variance explained by X #55

Open
shaorray opened this issue Aug 9, 2020 · 0 comments
Open

Percent of Y variance explained by X #55

shaorray opened this issue Aug 9, 2020 · 0 comments

Comments

@shaorray
Copy link
Contributor

shaorray commented Aug 9, 2020

Often in correlation tests, people will use %variance explained to described X and Y relationship.

e.g. transcription explained 71% gene expression variance.

So here are two functions could be useful:

  1. simple R2 concept

single_variance_explained <- function(X, Y, is.cor = F) {
stopifnot(length(X) == length(Y))
rm.idx = is.na(X) | is.infinite(X) | is.na(Y) | is.infinite(Y)
X = X[!rm.idx]
Y = Y[!rm.idx]
if (is.cor) return(cor(X, Y))
1 - var(Y - X) / var(Y)
}

  1. R2 decomposition of regression through origin
    X: n-row matrix with k features, Y: n responses

multi_variance_explained <- function(X, Y){
stopifnot(var(Y) > 0 & length(Y) == nrow(X))
X_tilde = cbind(1, scale(X)) # add an intercept error term ε
Y_tilde = scale(Y)
beta_hat = solve(t(X_tilde) %*% X_tilde) %*% t(X_tilde) %*% Y_tilde
c(beta_hat * t(cov(Y_tilde, X_tilde)))[-1]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant