Reputation: 3
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)
Upvotes: 0
Views: 151
Reputation: 545588
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])
}
Upvotes: 1