Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap an R function that accepts a scalar so it will accept a vector?

Tags:

r

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.

like image 400
Contango Avatar asked Sep 06 '25 05:09

Contango


1 Answers

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.

like image 103
Contango Avatar answered Sep 09 '25 02:09

Contango