Spacedman
Spacedman

Reputation: 94237

Applying over a vector of functions

Given a vector (actually a list) of functions:

 fs = c(sin, cos, tan)

and a vector of values:

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

Is there a better/neater/faster/stronger way of computing fs[[i]](xs[i]) for each vector element:

 vapply(1:3, FUN.VALUE = 1 ,function(i){fs[[i]](xs[i])})
  [1] 0.09983342 0.95533649 0.54630249

Or am I missing a fapply function somewhere? The functions will always be functions of a single scalar value and returning a single scalar value.

Upvotes: 11

Views: 292

Answers (2)

Josh O'Brien
Josh O'Brien

Reputation: 162411

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

Upvotes: 8

Roland
Roland

Reputation: 132959

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.

Upvotes: 8

Related Questions