s-news
[Top] [All Lists]

Re: Integration in a function

To: Ping Zhang <pingzhang@avaya.com>
Subject: Re: Integration in a function
From: Sundar Dorai-Raj <sundar.dorai-raj@PDF.COM>
Date: Wed, 28 Apr 2004 14:14:52 -0500
Cc: "Zhan, Ping N." <Ping.Zhan@celera.com>, s-news@lists.biostat.wustl.edu
In-reply-to: <1083179199.25215.8.camel@pzhang-pcl.research.avayalabs.com>
Organization: PDF Solutions, Inc.
References: <B97FA25EDA418049A146320ADFE65506022CCC90@celmrkv2.rkv.ad.celera.com> <1083179199.25215.8.camel@pzhang-pcl.research.avayalabs.com>
Reply-to: sundar.dorai-raj@PDF.COM
User-agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)


Ping Zhang wrote:

The problem appears to be that function calls failed to pass
objects. I am not sure if there is a better solution, but here
is a quick one. Basically if you make all variables global with where=0,
then you can access them anywhere in the program.




fx<-function(a,b,A,B)
{
assign("a",a,where=0)
assign("b",b,where=0)
assign("A",A,where=0)
assign("B",B,where=0)
gx<-function(x,...)
{
x^3*(1-x)^3*x^a*(1-x)^b/((1+(A/B-1)*x)^(a+b))
}
L<-(a/A)/(a/A+b/B)
numer<-integrate(gx,L,1)$integral
denom<-integrate(gx,0,1)$integral
return(c(numer/denom))
}




Or alternatively:

fx <- function(a,b,A,B) {
  gx <- function(x, a, b, A, B) {
    x^3*(1-x)^3*x^a*(1-x)^b/((1+(A/B-1)*x)^(a+b))
  }
  L <- (a/A)/(a/A+b/B)
  numer <- integrate(gx, L, 1, a = a, b = b, A = A, B = B)$integral
  denom <- integrate(gx, 0, 1, a = a, b = b, A = A, B = B)$integral
  numer/denom # `return' not needed if it's the last line
}

This explicitly passes the variables a, b, A, and B to the function gx.

(Note the spaces and indentation. Makes it much easier to read.)

--sundar


On Wed, 2004-04-28 at 14:41, Zhan, Ping N. wrote:

Hi All,

I have the following function defined with parameters a,b,A,B

fx<-function(a,b,A,B)
{
        gx<-function(x,...)
        {
                x^3*(1-x)^3*x^a*(1-x)^b/((1+(A/B-1)*x)^(a+b))
        }
        L<-(a/A)/(a/A+b/B)
        numer<-integrate(gx,L,1)$integral
        denom<-integrate(gx,0,1)$integral
        return(c(numer/denom))
}

However, when I tried to run the line below, I got an error message.

fx(a=120,b=120,A=10000,B=10000)

Problem in f(c(0.75, 0.502136157219797, 0.997863842780203,..: Object "a"
not found Use traceback() to see the call stack

It looks like that values of a,b,A and B didn't pass on. Can anyone tell
me how to fix it? Many thanks. I am using windows version splus 6.1.

Thanks,
Ping

--------------------------------------------------------------------
This message was distributed by s-news@lists.biostat.wustl.edu.  To
unsubscribe send e-mail to s-news-request@lists.biostat.wustl.edu with
the BODY of the message:  unsubscribe s-news


<Prev in Thread] Current Thread [Next in Thread>