# [R] Integrate functions with loops

Prof Brian Ripley ripley at stats.ox.ac.uk
Fri Sep 16 17:37:47 CEST 2005

```Try to give a vector result with one element for each of element of x,
e.g.

integrandtotest <- function(x) colSums(outer(t, x, "^"))

works, although in fact this integration can be done analytically (it is a
sum of exponentials).

On Fri, 16 Sep 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
> 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
> 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
>
>
>
> Alan Brennan
> Director of Health Economics and Decision Science
> http://www.shef.ac.uk/scharr/sections/heds
> ScHARR
> School of Health and Related Research
> University of Sheffield
> Regent Ct
> 30 Regent St
> Sheffield S1 4DA
> Tel:+44 (0)114 2220684
> Fax:+44 (0)114 2724095
> e-mail:a.brennan at sheffield.ac.uk
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
>

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

```