Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying over a vector of functions

Tags:

r

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.

like image 923
Spacedman Avatar asked May 06 '14 13:05

Spacedman


People also ask

What is the difference between a vector and a function?

A vector is a type of datatype and has its own importance. But, using a datatype with function totally changes its meaning and use. We have to develop a code using function only once and you can use that code anytime. There is no need to write code, again and again, as the larger program will store it in two or more functions.

What are the applications of vectors?

Applications of Vectors include Real Life applications, application of vector space, application of vector algebra, application of vector in Engineering, application of dot product of vectors and much more. In this article, we will study all the applications of vectors.

How to create a list of vectors over a specified range?

To create a list of vectors over a specified range, we use the colon (:) symbol. The code 1:5 gives you a vector with the numbers 1 to 5, and 2:–5 create a vector with the numbers 2 to –5. b) Using the seq (), we make steps in a sequence. Seq () function is used to describe the intervals by which numbers should decrease or increase.

How to apply a function over a list in R?

R: Apply a Function over a List or Vector lapply {base} R Documentation Apply a Function over a List or Vector Description lapplyreturns a list of the same length as X, each element of which is the result of applying FUNto the corresponding element of X.


2 Answers

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.

like image 54
Roland Avatar answered Sep 28 '22 00:09

Roland


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
like image 23
Josh O'Brien Avatar answered Sep 28 '22 01:09

Josh O'Brien