# [R] repeat a function

PIKAL Petr petr.pikal at precheza.cz
Fri Nov 3 08:54:17 CET 2017

```Hi

Well, I am not an expert in this field so I cannot comment your approach. I wanted only to point out that building matrix your way is like scratching your left ear with right hand, especially in R. What if you want increase size of your matrix?

E.g. you use function ProbUP once for row "0" and than for rows different from jmax (if I correctly understand your code). Use of any function depends on two parameters (row and column, let them call u and v)

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

Functions are quite similar, you basically need to find how combination of row and column number results in desired j value. However it could be quite tricky and if your approach works and you do not want to extend it or to make it more general, you could stay with it.

Cheers
Petr

> -----Original Message-----
> From: Eric.Pueyo at avivainvestors.com [mailto:Eric.Pueyo at avivainvestors.com]
> Sent: Thursday, November 2, 2017 5:54 PM
> To: PIKAL Petr <petr.pikal at precheza.cz>; r-help at r-project.org
> Subject: RE: [R] repeat a function
>
> Hi Petr,
>
> Many thanks for your response.
>
> Basically I want to create a probability matrix to be used in a trinomial tree
> going forward. This is the reason why I thought to build the matrix around 0
> would be much more efficient. I need to loop through because the probabilities
> will depend on my node and is not always the same per row (e.g. if N> jmax,
> jmax being defined in another function) I found a workaround. Please see
> below.
> Thereafter I want to optimize this function. Hopefully it works.
>
> Many thanks,
> Eric
>
> HWMProb <- function(N) {
>   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 (N>jmax) N=jmax
>
> for (j in 0:N) {
>   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
> } #end for
> }
>
>
> -----Original Message-----
> From: PIKAL Petr [mailto:petr.pikal at precheza.cz]
> Sent: 02 November 2017 15:56
> To: Eric Pueyo; r-help at r-project.org
> Subject: RE: [R] repeat a function
>
> 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)
> >
> > }
> >
> >

________________________________
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.
```