Search code examples
rvariablesintegral

integrate from 0 to a variable in r


I would like to plot y against z, where y=(1+z)int_0^z((0.3(1+z')^3+0.7)^-1/2)dz',

where int_0^z just means integrate from 0 to z. I figured I should first integrate from 0 to z, and then use the integral result to plug into the equation. Here is my code:

integrand <- function(z1) {(0.3*(1+z1)^3+0.7)^-1/2}
integral<-integrate(integrand, lower = 0, upper = z)

but this error appears:

Error: object 'any_number' not found

Error in integrate(integrand, lower = 0, upper = z) : object 'z' not found"

How do I define z here?

Thanks,

Jade


Solution

  • I'll give it a try.

    integrand <- function(z1) {(0.3*(1+z1)^3+0.7)^-1/2}
    

    We need to make integral a function of z, ensure that it only returns the value of the integral, and that it is vectorized in z:

    integral <- Vectorize(function(z) integrate(integrand, lower = 0, upper = z)$value)
    

    Now we can test it:

    integral(1:2)
    #[1] 0.3056435 0.4037815
    

    And plot:

    curve(integral, 0, 10, xname = "z")
    

    resulting plot