[R] repeat a function

Bert Gunter bgunter.4567 at gmail.com
Thu Nov 2 18:08:56 CET 2017


Petr et al. :

I only wish to comment on Petr's remark; I have nothing useful to say about
the subject of this thread.

"AFAIK if a function is defined within another function (which is your
case) it cannot be called directly so it is necessary to define it in
global environment."

Right, a deliberate consequence of R's (lexical) scoping semantics.
However, as you are probably aware, a function can *return* a function that
is then visible and can be called in the caller's scope. e.g. , using your
example:

> fff <- function(a){
    function(x) x^2 + a
 }

> fff(2)(3) ## note syntax: 3^2 + 2
[1] 11

> fff(3)(2) ## 2^2 + 3
[1] 7

## or you can assign the function to a symbol and call it directly

> myf <- fff(2)

> myf(3) ## 3^2 + 2
[1] 11


You all can decide whether or not this is useful in the current context.

Cheers,
Bert



Bert Gunter

"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

On Thu, Nov 2, 2017 at 8:56 AM, PIKAL Petr <petr.pikal at precheza.cz> wrote:

> Hi Eric
>
> I did not see any answer and frankly speaking I cannot provide you with
> canned help.
>
> AFAIK if a function is defined within another function (which is your
> case) it cannot be called directly so it is necessary to define it in
> global environment.
>
> >  fff <- function(x) {
> +  myf <- function(a) a+2
> +  myf(x)^2}
> >
> > fff(5)
> [1] 49
> > myf(5)
> Error in myf(5) : could not find function "myf"
> >
>
> Your function set is quite complicated but I wonder why would it be
> necessary to use for cycle for what seems to be simple table. Everything
> seems quite deterministic.
>
> Basically you have combination of rows (-2,-1,0,1,2) and columns -1,-,1.
> expand.grid(u=-2:2, v=-1:1)
> for each row you can than use one function with parameters u, v and a and
> dt.
> After you calculate vector of results, you can easily transform it to
> matrix by setting dim argument to it.
>
> Cheers
> Petr
>
> > -----Original Message-----
> > From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of
> > Eric.Pueyo at avivainvestors.com
> > Sent: Wednesday, November 1, 2017 1:31 PM
> > To: r-help at r-project.org
> > Subject: [R] repeat a function
> >
> > I want to populate the matrix prb through the function HWMProb <-
> function
> > (a,j,dt) that encapsulates different functions (please see code below),
> using j=
> > 0:2 for each j.
> >
> > It only populates prb if I specify each function independently in the
> global
> > environment and then run the loop with the iF statement, as per below.
> > for (j in 0:2) {
> >   if (j==0) {
> >     prb["0","1"] <- ProbUP(a,j,dt)
> >     prb["0","0"] <- ProbMID(a,j,dt)
> >     prb["0","-1"] <- ProbDWN(a,j,dt)
> >   }
> >   else {
> >     if (j==jmax) {
> >       prb[paste(j,sep = ""),"1"] <- TOPProbUP(a,j,dt)
> >       prb[paste(j,sep = ""),"0"] <- TOPProbMID(a,j,dt)
> >       prb[paste(j,sep = ""),"-1"] <- TOPProbDWN(a,j,dt)
> >       prb[paste(-j,sep = ""),"1"] <- BTTMProbUP(a,-j,dt)
> >       prb[paste(-j,sep = ""),"0"] <- BTTMProbMID(a,-j,dt)
> >       prb[paste(-j,sep = ""),"-1"] <- BTTMProbDWN(a,-j,dt)
> >     }
> >     else {
> >       prb[paste(j,sep = ""),"1"] <- ProbUP(a,j,dt)
> >       prb[paste(j,sep = ""),"0"] <- ProbMID(a,j,dt)
> >       prb[paste(j,sep = ""),"-1"] <- ProbDWN(a,j,dt)
> >       prb[paste(-j,sep = ""),"1"] <- ProbUP(a,-j,dt)
> >       prb[paste(-j,sep = ""),"0"] <- ProbMID(a,-j,dt)
> >       prb[paste(-j,sep = ""),"-1"] <- ProbDWN(a,-j,dt)
> >     } # Close 2nd IF
> >   } # Close 1st IF
> > }
> >
> > Many thanks in advance.
> > Kind regards,
> >
> > Eric Pueyo
> > Investment Risk Analyst
> > Email:
> > Eric.Pueyo at avivainvestors.com<mailto:Eric.Pueyo at avivainvestors.com>
> > D: +44 (0)20 7809 8070
> > No. 1 Undershaft, London EC3P 3DQ
> > Web:
> > www.avivainvestors.com<https://urldefense.proofpoint.com/v2/url?u=http-
> > 3A__www.avivainvestors.com_&d=CwMFAg&c=zUO0BtkCe66yJvAZ4cAvZg&r=-
> > 34SVFvqwmZvbxD0ShuYglbuijP84lygitjFgiP1fxI&m=kRg3I7ESFxV-
> > KaNbYHN6DPupgyEmFCiThNO6oDnpAFs&s=tQa1EuXKNfzRgiR2HgG0H_tW_X-
> > BCpgebe5AL9A_GC8&e=>
> >
> > jmax<-2
> > prb <-matrix(0L,nrow=5, ncol=3)
> > rownames(prb) <- c(seq(-2,2, by = 1))
> > colnames(prb) <- c(-1,0,1)
> > a<- 0.1
> > dt<-1
> >
> > ExpX <-function(x,a,dt) {                              ######Defines the
> Expectation of X
> > on t+1 | t
> > ExpX <- x*exp(-a*dt)
> > ExpX
> > }
> > Mfactor<-function(a,dt)  {                           #######Factor
> multiplicative
> >   Mfactor<- exp(-a*dt)-1
> >   Mfactor
> > }
> > VarX <-function(sigma,a,dt) {                         #######Defubes the
> Variance of X
> > on t+1 | t
> >   VarX <- (sigma^2/(2*a))*(1-exp(-2*a*dt))
> >   VarX
> > }
> > DeltaX <-function(sigma,a,dt) {                       ######Defines the
> change of X
> >   DeltaX<- sqrt(3*VarX(sigma,a,dt))
> >   DeltaX<-value(DeltaX)
> > }
> >
> > Mfactor<-function(a,dt)  {                           #######Factor
> multiplicative
> >   Mfactor<- exp(-a*dt)-1
> >   Mfactor
> > }
> >
> > KNode<-function(sigma,x,a,j,dt) {                    ######Central Node
> >   KNode<- round(ExpX(x,a,dt)/DeltaX(sigma,a,dt))
> >   KNode
> > }
> >
> > ####### Probability Calculations taking into account different branches
> > HWMProb <- function (a,j,dt) {
> >   ######################### DESCRIPTION
> > #####################################
> >   ProbUP<- function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 + j
> * Mfactor(a,
> > dt)) / 2)                     ######### Probability X going up
> >   ProbMID<- function(a, j, dt) 2 / 3 - (j ^ 2 * Mfactor(a, dt) ^ 2)
> > ######## Probability X going middle
> >   ProbDWN<-function( a, j, dt) 1 / 6 + ((j ^ 2 * Mfactor(a, dt) ^ 2 - j
> * Mfactor(a,
> > dt)) / 2)                  #######  Probability X going down
> >   TOPProbUP<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 +
> 3 * j *
> > Mfactor(a, dt)) / 2                 ####### Top branch probability going
> up
> >   TOPProbMID<- function(a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2 -
> 2 * j *
> > Mfactor(a, dt)              ####### Top branch probability going MID
> >   TOPProbDWN<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 +
> j *
> > Mfactor(a, dt)) / 2               ####### Top branch probability going
> DOWN
> >   BTTMProbUP<- function( a, j, dt) 1 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2 -
> j *
> > Mfactor(a, dt)) / 2           ####### Bottom branch probability going u
> >   BTTMProbMID<- function( a, j, dt) -1 / 3 - j ^ 2 * Mfactor(a, dt) ^ 2
> + 2 * j *
> > Mfactor(a, dt)               ####### Bottom branch probability going MID
> >   BTTMProbDWN<- function( a, j, dt) 7 / 6 + (j ^ 2 * Mfactor(a, dt) ^ 2
> - 3 * j *
> > Mfactor(a, dt)) / 2              ####### Bottom branch probability going
> DOWN
> >
> >   if (j==0) {
> >     prb["0","1"] <- ProbUP(a,j,dt)
> >     prb["0","0"] <- ProbMID(a,j,dt)
> >     prb["0","-1"] <- ProbDWN(a,j,dt)
> >   }
> >   else {
> >     if (j==jmax) {
> >       prb[paste(j,sep = ""),"1"] <- TOPProbUP(a,j,dt)
> >       prb[paste(j,sep = ""),"0"] <- TOPProbMID(a,j,dt)
> >       prb[paste(j,sep = ""),"-1"] <- TOPProbDWN(a,j,dt)
> >       prb[paste(-j,sep = ""),"1"] <- BTTMProbUP(a,-j,dt)
> >       prb[paste(-j,sep = ""),"0"] <- BTTMProbMID(a,-j,dt)
> >       prb[paste(-j,sep = ""),"-1"] <- BTTMProbDWN(a,-j,dt)
> >     }
> >     else {
> >       prb[paste(j,sep = ""),"1"] <- ProbUP(a,j,dt)
> >       prb[paste(j,sep = ""),"0"] <- ProbMID(a,j,dt)
> >       prb[paste(j,sep = ""),"-1"] <- ProbDWN(a,j,dt)
> >       prb[paste(-j,sep = ""),"1"] <- ProbUP(a,-j,dt)
> >      prb[paste(-j,sep = ""),"0"] <- ProbMID(a,-j,dt)
> >       prb[paste(-j,sep = ""),"-1"] <- ProbDWN(a,-j,dt)
> >     } # Close 2nd IF
> >   } # Close 1st IF
> > } #Close Formula
> >
> > for (j in 0:2) {
> >   HWMProb(a,j,dt)
> >
> > }
> >
> >
> >       [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
> ________________________________
> Tento e-mail a jakékoliv k němu připojené dokumenty jsou důvěrné a jsou
> určeny pouze jeho adresátům.
> Jestliže jste obdržel(a) tento e-mail omylem, informujte laskavě
> neprodleně jeho odesílatele. Obsah tohoto emailu i s přílohami a jeho kopie
> vymažte ze svého systému.
> Nejste-li zamýšleným adresátem tohoto emailu, nejste oprávněni tento email
> jakkoliv užívat, rozšiřovat, kopírovat či zveřejňovat.
> Odesílatel e-mailu neodpovídá za eventuální škodu způsobenou modifikacemi
> či zpožděním přenosu e-mailu.
>
> V případě, že je tento e-mail součástí obchodního jednání:
> - vyhrazuje si odesílatel právo ukončit kdykoliv jednání o uzavření
> smlouvy, a to z jakéhokoliv důvodu i bez uvedení důvodu.
> - a obsahuje-li nabídku, je adresát oprávněn nabídku bezodkladně přijmout;
> Odesílatel tohoto e-mailu (nabídky) vylučuje přijetí nabídky ze strany
> příjemce s dodatkem či odchylkou.
> - trvá odesílatel na tom, že příslušná smlouva je uzavřena teprve
> výslovným dosažením shody na všech jejích náležitostech.
> - odesílatel tohoto emailu informuje, že není oprávněn uzavírat za
> společnost žádné smlouvy s výjimkou případů, kdy k tomu byl písemně zmocněn
> nebo písemně pověřen a takové pověření nebo plná moc byly adresátovi tohoto
> emailu případně osobě, kterou adresát zastupuje, předloženy nebo jejich
> existence je adresátovi či osobě jím zastoupené známá.
>
> This e-mail and any documents attached to it may be confidential and are
> intended only for its intended recipients.
> If you received this e-mail by mistake, please immediately inform its
> sender. Delete the contents of this e-mail with all attachments and its
> copies from your system.
> If you are not the intended recipient of this e-mail, you are not
> authorized to use, disseminate, copy or disclose this e-mail in any manner.
> The sender of this e-mail shall not be liable for any possible damage
> caused by modifications of the e-mail or by delay with transfer of the
> email.
>
> In case that this e-mail forms part of business dealings:
> - the sender reserves the right to end negotiations about entering into a
> contract in any time, for any reason, and without stating any reasoning.
> - if the e-mail contains an offer, the recipient is entitled to
> immediately accept such offer; The sender of this e-mail (offer) excludes
> any acceptance of the offer on the part of the recipient containing any
> amendment or variation.
> - the sender insists on that the respective contract is concluded only
> upon an express mutual agreement on all its aspects.
> - the sender of this e-mail informs that he/she is not authorized to enter
> into any contracts on behalf of the company except for cases in which
> he/she is expressly authorized to do so in writing, and such authorization
> or power of attorney is submitted to the recipient or the person
> represented by the recipient, or the existence of such authorization is
> known to the recipient of the person represented by the recipient.
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/
> posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

	[[alternative HTML version deleted]]



More information about the R-help mailing list