Ben
Ben

Reputation: 4984

multiplying functions

Suppose I have two numeric functions in R. Eg., cos and exp. What is the fastest way to have a new function object f(x) = cos(x)*exp(x)? I could define this as

f <- function(x) {cos(x)*exp(x) }

but is there a shorthand way of doing this (f = cos*exp for example)

Upvotes: 3

Views: 653

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145775

If you're doing this a lot, you could define a binary operator:

"%*f%" = function(x, y) {
    force(x)
    force(y)
    function(z) x(z) * y(z)
}

f = cos %*f% exp
x = runif(10)

> identical(f(x), cos(x) * exp(x))
[1] TRUE

This has the advantage of being chain-able:

g <- cos %*f% exp %*f% log %*f% mean
g(x) # works appropriately

Upvotes: 6

Related Questions