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.
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.
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.
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.
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.
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.
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
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