I am trying to avoid using loops using apply to apply a user-defined function to the matrix. The problem is that there are additional parameters that my function uses, and they differ for each column of the matrix. Below is an example of toys.
Let's say I have the following function:
foo <- function(x, a, b, c) return( (a*x + b)^c )
and I want to apply it to the bar matrix 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 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 not true, since each column uses all the parameters sequentially before returning to the first parameter again. Any suggestions?
r apply
Lyngbakr
source share