Applying over a vector of functions

后端 未结 2 1583
野性不改
野性不改 2020-12-16 17:52

Given a vector (actually a list) of functions:

 fs = c(sin, cos, tan)

and a vector of values:

 xs = c(.1, .3, .5)


        
相关标签:
2条回答
  • 2020-12-16 18:33

    Nice and simple:

    mapply(function(fun, x) fun(x), fs, xs)
    

    But I agree with @flodel. I was also looking for a base function for function(fun, ...) fun(...) and was surprised that there doesn't seem to be one. On the other hand I've never needed it, so far.

    0 讨论(0)
  • 2020-12-16 18:41

    Here's an alternative whose main advantage over the suggestions so far is that it doesn't require that an anonymous function be defined.

    mapply(do.call, fs, lapply(xs, list))
    # [1] 0.09983342 0.95533649 0.54630249
    
    0 讨论(0)
提交回复
热议问题