Jason Mathews
Jason Mathews

Reputation: 275

How to pass another function as a variable to apply function in R?

So I want to apply a function over a matrix in R. The apply function takes a custom function that takes two parameters: element of a matrix and sum of the row that element belongs to. Below is the reproducible code

m = (matrix(1:10, nrow=2))
## Custom Function
IC = function(element, sum_rows){
  value = -log(element/sum_rows,2)
  return(value)
}

I am wondering if there is any way of passing rowSums as a parameter to apply function like below

apply(m,1:2,IC,sum_rows = rowSums)

Upvotes: 0

Views: 102

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99391

When applying element-by-element (with MARGIN = 1:2), the rowSums function won't work because there are no rows. Each element is an atomic vector.

Fortunately, this operation can be fully vectorized and log2 can be used for a binary (base 2) logarithm.

-log2(m / rowSums(m))
#          [,1]     [,2]     [,3]     [,4]     [,5]
# [1,] 4.643856 3.058894 2.321928 1.836501 1.473931
# [2,] 3.906891 2.906891 2.321928 1.906891 1.584963

Upvotes: 3

Related Questions