[R] Integrate functions with loops
A.Brennan
A.Brennan at sheffield.ac.uk
Fri Sep 16 17:21:00 CEST 2005
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
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
More information about the R-help
mailing list