[R] Applying a function to a vector

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon Oct 31 16:39:33 CET 2005


On Mon, 31 Oct 2005, Thomas Lumley wrote:

> On Mon, 31 Oct 2005, Florent Bresson wrote:
>
>> I just have a try with sapply. The problem is that my
>> function pbeta2 has two parameters z and p (wich is a
>> vector of two parameters). If I use sapply , R returns
>> a message incicating that parameter p is missing. It
>> is a problem since both z and p are varying along my
>> data.frame.
>
> You would need mapply().  It won't help, though.  Most of the time is 
> presumably being spent in all the calls to integrate, so mapply() or sapply() 
> won't be much faster than a loop.
>
>
> According to Google, the VGAM R package http://www.stat.auckland.ac.nz/~yee/
> claims to have the beta distributions of the second kind.

It has ML fitting for such distributions.

I think a reasonable answer is to make a function to approximate the 
indefinite integral via linear or spline interpolation.  Then you can 
replace 22,000 numerical integrations by interpolation from a few hundred 
values (at most).


>>> On Mon, 31 Oct 2005, Florent Bresson wrote:
>> 
>>>> beta distribution of the second kind (the existing
>>>> beta distribution of th stats package is the beta
>>>> distribution of the first kind). It works perfectly
>>>> for a single value, but I want to apply it to a
>> vector
>>>> of 22 000 values. I can use a loop for the
>> calculation
>>>> of each value but it runs very very slowly.
>>>> So, what can I change ?
>>>> 
>>>> Here's the function :
>>>> p <-  c(1,1)
>>>> y <-  1
>>>> z <-  1
>>>> truc  <-  function(y)
>> {y^(p[1]-1)/(1+y)^(p[1]+p[2])}
>>>> pbeta2  <-  function(z,p)
>>>> 1/beta(p[1],p[2])*integrate(truc,0,z)$value
>>>> 
>>>> machin <- pbeta2(vector,p) just return a single
>> value

-- 
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




More information about the R-help mailing list