I'm trying to avoid using loops by using apply
to apply a user-defined function to a matrix. The problem I have is that there are additional parameters that my function uses and they differ for each column of the matrix. Below is a toy example.
Say I have the following function:
foo <- function(x, a, b, c) return( (a*x + b)^c )
and I want to apply it to a matrix bar
using different values of a
, b
, and c
for each column.
bar <- matrix(1:15, ncol = 3)
a <- 4:6
b <- 3:1
c <- 1:3
In this case, for the first column of bar
, then a=4
, b=3
, and c=1
. I tried this,
apply(bar, 2, foo, a=a, b=b, c=c)
but this is clearly incorrect, as each column uses all parameters sequentially before wrapping back to the first parameter again. Any suggestions?
We could split
the 'bar' by 'column' (col(bar)
) and with mapply
we can apply 'foo' for the corresponding 'a', 'b', 'c' values to each column of 'bar'
mapply(foo, split(bar, col(bar)), a, b, c)
Or without using apply
ind <- col(bar)
(a[ind]*bar +b[ind])^c[ind]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With