[R] Integrate functions with loops
Sundar Dorai-Raj
sundar.dorai-raj at pdf.com
Fri Sep 16 17:31:35 CEST 2005
A.Brennan wrote:
> Hi
>
> i am having a problem with the 'integrate' function
> the function i want to integrate has the form
> sum(vector^x)
>
> i have defined the function with a for loop first -
> integrandtotest <- function(x)
> {a<-rep(0,len=2)
> for (i in 1:2)
> {a[i]<-t[i]^x}
> sum(a)
> }
>
> the results gives errors
> ###########
> Error in integrate(integrandtotest, lower = 0.1, upper = 2,
> subdivisions = 10000) :
> evaluation of function gave a result of wrong length
> In addition: Warning messages:
> 1: number of items to replace is not a multiple of replacement
> length
> 2: number of items to replace is not a multiple of replacement
> length
> #######
>
> I then tried a vector multiplication instead of the for loop
>
>
> integrandtotest3 <- function(x)
> {b<-c(t[1],t[2])
> a<-b^x
> sum(a)
> }
>
> which gave errors
> ########
> Error in integrate(integrandtotest3, lower = 0.1, upper = 2,
> subdivisions = 10000) :
> evaluation of function gave a result of wrong length
> In addition: Warning message:
> longer object length
> is not a multiple of shorter object length in: b^x
> ##########
>
> but when i write the functio out long-hand as follows:
>
> integrandtotest2 <- function(x)
> {t[1]^x+t[2]^x}
>
> the integrate function works perfectly.......
> ###
>
>>integralresulttotest2<-integrate(integrandtotest2, lower=0.1,
>
> upper=2, subdivisions=10000)
>
>>integralresulttotest2
>
> 1.642369 with absolute error < 1.8e-14
> ###
>
> Unfortunatley my real life example has the vector a with length at
> least 100.
>
> Is the any way round these errors?
>
> Many thanks for answers to my first question to this list
> yours
> Alan
>
Hi, Alan,
It might help if you print(x) in your integrate function.
integrandtotest <- function(x) {
print(x)
a <- rep(0, len=2)
for(i in 1:2) {
a[i] <- tt[i]^x
}
sum(a)
}
integrate(integrandtotest, lower = 0.1, upper = 2)
You will see that "x" is a vector and "tt[i]^x" returns a vector of the
same length. You are trying to place this vector into "a[i]" which is
length 1. Try the following *untested* code instead:
<untested>
integrandtotest <- function(x) {
sum(sapply(x, function(xi) sum(tt^xi)))
}
integrate(integrandtotest, lower = 0.1, upper = 2)
</untested>
Also, I would avoid using "t" as a variable name. "t" is also a
function. Most of the time R can tell the difference, but sometimes it
cannot.
HTH,
--sundar
More information about the R-help
mailing list