I want to save the integral values in an array. Say,from q=1
to q=10
in the following program. But due to output with a non-numeric part, I can't do so.
q=10
integrand<-function(x)(q*x^3)
integrate(integrand,lower=0,upper=10)
the output is "25000 with absolute error < 2.8e-10"
How can I remove the non-numeric part?
str()
is your friend to figure this out:
> intval <- integrate(integrand,lower=0,upper=10)
> str(intval)
List of 5
$ value : num 25000
$ abs.error : num 2.78e-10
$ subdivisions: int 1
$ message : chr "OK"
$ call : language integrate(f = integrand, lower = 0, upper = 10)
- attr(*, "class")= chr "integrate"
So you can see that you need the value
element:
> intval$value
[1] 25000
Then:
integrand <- function(x, q=10) { q*x^3 }
tmpfun <- function(q) {
integrate(integrand,lower=0,upper=10,q=q)$value
}
sapply(1:10,tmpfun)
## [1] 2500 5000 7500 10000 12500 15000 17500 20000 22500 25000
I hope this is a simplified example, because this particular answer is much more simply obtained by (1) integrating analytically and (2) realizing that a scalar multiple can be taken out of an integral: 1:10*(10^4/4)
gets the same answer.