rnumerical-integration

Integrate a function in R through time


I would like to integrate the following function with respect to t, for lower bound = 0 and upper bound = t. I can do that with the following code, but my ultimate goal is to have a value of the integral for each t. Even if I make t a sequence instead of a value, or if I try and use sapply, I still cannot get a value for the integral at each step of t.

#initialize constants
kap=-0.1527778
alph0<-6
b<-0
po<-0.01
t<-100
gp_st<-integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=t)$value

#try alternate where t is now a sequence 
t<-seq(1:100)
gp_st2<-function(h) sapply(h,gp_st) #still gives length of 1

Thanks!


Solution

  • Try making gp_st a function of your upper bound, like so:

    gp_st <- function(h) {
      integrate(function(t) (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap),lower=0,upper=h)$value
    }
    

    Then you can use sapply much as you intended:

    t<-seq(1:100)
    gp_st2 <- sapply(t, gp_st)
    

    and now gp_st2 is a numeric vector of length 100.