A version of Vectorize() for apply() rather than mapply()?
Is there a version of Vectorize
that uses apply
rather than mapply
?
I wo开发者_如何转开发uld like to vectorize a function that takes vector input in a way that allows me
to pass an array to that function and have a vector returned.
Of course I can write my own wrapper and that works well enough. But I wondered if this functionality is built in?
I can also use Vectorize
, but then I have to convert the matrix input to a data.frame for it work. For example:
LAMBDA <- cbind(c(1, .5, .5), c(.5, 1, .5), c(.5, .5, 1))
THETA <- c(0,0,1)
NU <- 21
my.data <- array(1:6, c(3,2))
my.fun <- Vectorize(pmt, vectorize.args="x")
Then
> my.fun(my.data, mean=THETA, S=LAMBDA, df=NU)
[1] 0.4404142 0.8130572 0.9667065 0.9961166 0.9996274 0.9999676
Which is not what I want, but
> my.data <- data.frame(my.data)
> my.fun(my.data, mean=THETA, S=LAMBDA, df=NU)
X1 X2
0.8130572 0.9996274
is what I want.
BTW, pmt
is from the mnormt package and is a multivariate student's t cdf.
It seems like you want to define a function my.fun
to which you pass in a matrix my.data
, and the my.fun
will just "know" that it needs to apply the function to each column of my.data
. This is what the apply()
function is meant to do; you don't need the Vectorize
call. So why not just do this:
my.data <- array(1:6, c(3,2))
> apply(my.data, 2, pmt, mean=THETA, S=LAMBDA, df=NU)
[1] 0.8130572 0.9996274
精彩评论