[R] R object as a function

Tim Hesterberg timh at insightful.com
Wed Jan 23 17:10:40 CET 2008


This function is a vectorized alternative to integrate:

CumIntegrate <- function(f, a = 0, b = 1, nintervals = 5, ...){
  # Cumulative integral.  f is a function, a and b are endpoints
  # return list(x,y) of two vectors,	
  # where x = seq(a, b, length = nintervals)
  # and   y = \int_a^{x} f(t) dt
  #
  # 10-point Gaussian on each of nintervals subintervals
  # Assume that f can take a vector argument
  ends <- seq(a, b, len = nintervals + 1)
  h <- (b - a)/(2 * nintervals)	   #half-width of a single subinterval
  mids <- (ends[-1] + ends[1:nintervals])/2
  x <- c(0.14887433898163099, 0.43339539412924699, 0.67940956829902399,
	0.86506336668898498, 0.97390652851717197)
  wt <- c(0.29552422471475298, 0.26926671930999602, 0.21908636251598201,
	 0.149451349150581, 0.066671344308687999)
  xvalues <- outer(h * c( - x, x), mids, "+")
  list( x = ends,
       y = c(0,h*cumsum(colSums( matrix( wt*f(c(xvalues), ...), 10)))))
}

Tim Hesterberg

>On 22/01/2008 5:30 AM, Thomas Steiner wrote:
>> I want to use a function as an argument to ingtegrate it twice.
>> ...

Duncan Murdoch wrote:
>...
>The other problem is that integrate is not vectorized, it can only take 
>scalar values for lower and upper, so you'll need a loop within innerFkn 
>to do the integral over the values being passed in.



More information about the R-help mailing list