简体   繁体   English

R:函数内的递归函数

[英]R: Recursive function within function

For my likelihood function, the denominator is defined by the recursive function recurseG for each observation (1:N). 对于我的似然函数,分母由每个观察值的递归函数recurseG定义(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. 作为recurseG的输入的xG丢失了。 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. 您只需 fout函数中定义xG即可。 However, recurseG is defined outside it. 但是, recurseG在其外部定义。 The visibility of xG is constrained to the scope it is defined in, thus it is not visible in recurseG . xG的可见性recurseG定义范围的限制,因此在recurseG不可见。

To solve the problem, simply pass xG to recurseG as a parameter: 要解决此问题,只需将xG传递给recurseG作为参数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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