简体   繁体   中英

R: Recursive function within function

For my likelihood function, the denominator is defined by the recursive function recurseG for each observation (1:N).

If I loop over the function, everythings ok.

When I embed the procedure inside my main (likelihood)function, things get weird. xG, which is the input for recurseG, goes missing. Never seen that before, any ideas what the problem is? Cheers.

recurseG <- function(T,S){ # xG externally defined
  if (S==0) return(1)
  if (S>T) return(0)
  else return (Recall(T-1, S) + Recall(T-1, S-1)*xG[T])
}

# define for replication
N=10; T=3
x <- matrix(rnorm(N*T),N,T)
tG <- rep(T,N)
sG <- sample(rep(0:T,T), N)

## standalone

denom <- rep(NA, N)
for (i in 1:N){
  xG <- x[i,]
  denom[i] <- recurseG(tG[i], sG[i])
} 

## inside function

rm(xG) # will produce "not found"

fout <- function(x){
  denom <- rep(NA, N)
  for (i in 1:N){
    xG <- x[i,]
    denom[i] <- recurseG(tG[i], sG[i])
  } 
  return(denom)
}

denom
fout(x)

The problem has got nothing to do with recursion. You simply define xG inside your fout function. However, recurseG is defined outside it. The visibility of xG is constrained to the scope it is defined in, thus it is not visible in recurseG .

To solve the problem, simply pass xG to recurseG as a parameter:

recurseG <- function(T, S, xG) {
    if (S == 0) return(1)
    if (S > T) return(0)
    else return(Recall(T - 1, S, xG) + Recall(T - 1, S - 1, xG) * xG[T])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM