Integrate a Function in r

606 views Asked by At

I have the following function:

  Demandfunction_m1 <- function(y) {y<- exp(coefm1[1,]+x*coefm1[2,])
  return(y)}

In the next step i want to calculate the area under the curve for every observation in my dataset.

I was able to integrate the fuction for every single observation. It looks like this (Every observation has its own limits of integration):

 obs1<-integrate(Demandfunction_m1,3,16)
 obs2<-integrate(Demandfunction_m1,5,12)
 obs3<-integrate(Demandfunction_m1,4,18)

...and so on

My dataset has 260 observations and i asked myself if there is an easier way to calcualate the areas under the curves.

I found this solution:

Integrate function with vector argument in R

surv <- function(x,score) exp(-0.0405*exp(score)*x) # probability of     survival
area <- function(score) integrate(surv,lower=0,upper=Inf,score=score)$value
v.area <- Vectorize(area)

scores <- c(0.5, 0.6, 0.7, 0.8, 0.9, 1, 1.1)  # 7 different scores
v.area(scores)
# [1] 14.976066 13.550905 12.261366 11.094542 10.038757  9.083443  8.219039

I tried to apply this to my R-Skript:

Demandfunction_m1 <- function(y) {y<- exp(coefm1[1,]+x*coefm1[2,])
return(y)}
area <- function(x)    integrate(Demandfunction_m1,lower=c(3,5,4),upper=c(16,12,18))$value
v.area <- Vectorize(area)

and then i don't know what i have to do next.

Do you have any suggestions?

1

There are 1 answers

0
Jean On

Your demand function doesn't make sense. You are passing it an argument y that you don't use to make any calculations...

Demandfunction_m1 <- function(x,a,b) {exp(a+x*b)}
area<-function(arg1, arg2, low, high) { integrate(Demandfunction_m1, lower=low, upper=high, a=arg1, b=arg2)$value }
v.area<-Vectorize(area)

lows<-c(3,5,4)
highs<-c(16,12,18)
result <- v.area(rep(coefm[1,],3), rep(coefm1[2,],3), lows, highs) 

#if you want to use different coefficients for a and b, just replace the repeated coef with a vector.
result <- v.area(c(1,2,3), c(10,9,8), lows, highs) 
#equivalent to integrate(exp(1 + x*10), lower=3, upper=16)), integrate(exp(2 + x*9), lower=5, upper=12)), integrate(exp(3 + x*8), lower=4, upper=18))