I have a function in R that accepts a scalar value quite nicely, but it doesn't accept a vector.
Is there any way to place a wrapper over it, so this wrapper function can accept a vector?
The function itself has 5 parameters.
What I've tried
I've tried every combination of sapply
, lapply
and mapply
I can think of, and R keeps on giving errors that are somewhat obscure, to say the least.
Got it.
The original function call is:
result<-MyFunc(P=34,S=100,X=100,T=1)
Method 1
To make this accept a vector input, simply add mapply
in front of the function call and convert the first opening bracket (
into a comma ,
:
result<-mapply(MyFunc,P=34,S=100,X=100,T=1)
Method 2
Thanks to @Roland, type ??Vectorize
to find a function that can wrap a function to make it accept vectors.
MyFuncOnVector <- Vectorize(MyFunc)
result <- MyFuncOnVector(P=34,S=100,X=100,T=1)
Behind the scenes, Vectorize is calling mapply
.
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