Last active
March 10, 2018 21:13
-
-
Save mikmart/85a5118285b1f8e4361399a1a3cb3034 to your computer and use it in GitHub Desktop.
Calculating summaries from arrays without loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
set.seed(1) | |
n <- 1000 | |
matrices <- replicate(n, matrix(runif(24 ^ 2), nrow = 24)) | |
str(matrices) | |
#> num [1:24, 1:24, 1:1000] 0.266 0.372 0.573 0.908 0.202 ... | |
f <- function(x) { | |
sum_x <- sum(x) | |
if (sum_x == 0) | |
return(0) | |
p <- x / sum_x | |
p[p == 0] <- 1 | |
-sum(p * log2(p)) | |
} | |
g <- function(x, i) { | |
apply(x, i, sum) / sum(x) * 2 ^ apply(x, i, f) | |
} | |
result <- apply(matrices, 3, g, 2) | |
str(result) | |
#> num [1:24, 1:1000] 0.926 0.867 0.849 0.89 0.853 ... | |
#' Created on 2018-03-06 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ah, yeah I see. Like you've done, just replacing the
NA
s inresult
with zeroes will produce the correct result; but still, it's probably cleaner to just deal with that in thef
function, too, so that we never divide by zero. If we add a check to see ifsum(x) == 0
inf
and return0
if so, we get the same result -- and don't have to do any clean up after!I'm happy to help! It's been interesting refreshing my array manipulations, since I normally just work with data frames and lists.