How to pass a function and a list of its vector arguments?
I'm trying to write a function in R that will take as arguments, a second
function and its arguments, some of which are vectors. The ultimate result
I want is to write a rolling function that calls a function to act on a
time series, but I've tried all permutations of "apply" functions I can
think of with no success, since "apply" functions all seem to apply a
function to a vector element by element and what I want is to apply
functions to vectors as a whole. For example,
a = c(1,2,3); b = c(4,5,6)
sapply(a,function(x,y,c) c*t(x)%*%y,b,c=2)
[,1] [,2] [,3]
[1,] 8 16 24
[2,] 10 20 30
[3,] 12 24 36
but what I really want is:
2*t(a)%*%b
[,1]
[1,] 64
and be able to roll the function along a time series. I've also tried
writing a generic function that contains a second function and its
parameters as arguments, but I can't seem to get it to accept the
parameters. For example,
foo <- function(func,parm){
return(func(parm))
}
foo(function(x,y,c) c*t(x)%*%y,parm=list(a,b,c=2))
Error in c * t(x) %*% y : 'c' is missing
The problem here is that func won't accept a list of arguments, but how
does one pass a list of arguments to a function? Hope this isn't too
confusing. Thanks for any help offered.
No comments:
Post a Comment