user801855
user801855

Reputation: 15

How do I have a function that multiplies 2 functions in r?

w         <- -1
pqxf      <- function(y)(1)*(y) # replace p with price of y
pqyf      <- function(x)(w*x)-(w*16) # -1.25 is the wage rate
utilityf  <- function(x)(80)*(1/(x)) # the utility function C,l
hours     <- c(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,20)

I'm trying to figure out how to multiply pqxf and pqyf, to make utilityf

Upvotes: 0

Views: 443

Answers (1)

Marius
Marius

Reputation: 60070

It's a bit hard to work out what utilityf should look like here, so let's use a simpler example. We have two functions square() and inverse(), and we want to do a calculation that involves squaring one set of numbers a, and multiplying by the inverse of another set of numbers b. First let's create the square and inverse functions:

square <- function(a) {
    a^2
}

inverse <- function(b) {
    1 / b
}

These are just functions, they won't do anything until we call them and pass them an input.

Here's what you tried to do in a previous version of this question:

output_bad <- function(a, b) {
    square * inverse
}

This doesn't work because we don't call the square and inverse functions at all, we don't give them inputs. So we end up trying to multiply one function object by another function object.

Here's the right way to do it:

output <- function(a, b) {
    square(a) * inverse(b)
}

We provide a and b as inputs to our output function, and call square and inverse on them to get the individual results from those functions, which we can then multiply together. Now we can pass different values of a and b to output:

> output(c(1, 2, 3), c(4, 5, 6))
# [1] 0.25 0.80 1.50

Upvotes: 2

Related Questions