0

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!

LauraR
  • 181
  • 1
  • 2
  • 12

2 Answers2

0

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.

Frank
  • 2,386
  • 17
  • 26
  • and now the next step... if I wanted to evaluate this function for several values of b, po, kap, alph0... i'm guessing there is a more efficient way to do this than nesting the apply statement in a loop for each parameter I'd like to vary? – LauraR Apr 11 '15 at 19:59
  • Vectorization may work (using vectors over all the values you want to try, and having the output be an array) but it may be conceptually unintuitive. Looping over the different combinations of parameters you want to try out isn't necessarily bad -- try it out and see what the runtime is. – Frank Apr 12 '15 at 20:46
0

The problem is that you are evaluating the integral in gp_st, and you don't want to do that. You want the following:

ff = function(t) {
  (1-alph0/(alph0+b*t)*(1-po^kap))^(1/kap)
}
sapply(1:100, function(ul) {
  integrate(ff, lower = 0, upper = ul)$value
})

There are naturally more efficient ways to do this.

jimmyb
  • 4,227
  • 2
  • 23
  • 26
  • thanks, now i'd like to evaluate the function for several values of the constants (alph0, b, po, kap). would you recommend storing these in a data frame and appending values for each parameter? – LauraR Apr 11 '15 at 20:04