using ifelse() in Nimble models

14 views
Skip to first unread message

Brook Milligan

unread,
Oct 28, 2025, 6:43:29 PM (5 days ago) Oct 28
to nimble-users
I have a model that uses a vector X of constants, some of which are NA. In the model, I calculate a deterministic function like:

x[1:n] <- ifelse(is.na(X[1:n]),A[1:n],B[1:n])

When X is passed to nimble as a constant, it complains with:

R function 'is.na' has arguments that cannot be evaluated in the code ‘is.na(X[1:n])'. Either the function must be a nimbleFunction or values for the following inputs must be specified as constants in the model: X[1:n].

The second part of this is misleadingly wrong, because X actually is passed as a constant. Passing as data yields the same.

Note that A and B above are expressions involving random variables and therefore cannot be calculated outside the nimble model.

How should this be handled? Is it possible?

Thanks for your help.

Cheers,
Brook



Daniel Turek

unread,
Oct 29, 2025, 11:24:39 AM (4 days ago) Oct 29
to Brook Milligan, nimble-users
Brook, it's true the error message is misleading.  The issue is stemming from the use of is.na() - even evaluated on X passed as a contestant - inside the ifelse() function, which also requires constant arguments.

There are certainly other ways of accomplishing what you're after, perhaps even more elegant, but below is a sketch of one idea.  If this doesn't work, I'm sure we can find other approaches.

Cheers,
Daniel


library(nimble)

X <- c(2, 4, 7, NA, 8, NA, 10)

NAs <- which(is.na(X))
n_NAs <- length(NAs)

nonNAs <- which(!is.na(X))
n_nonNAs <- length(nonNAs)

code <- nimbleCode({
    ## placeholders for definitinos of A and B:
    A[1:10] <- 1:10
    B[1:10] <- 11:20
    ##
    for(i in 1:n_NAs)
        x[NAs[i]] <- A[NAs[i]]
    for(i in 1:n_nonNAs)
        x[nonNAs[i]] <- B[nonNAs[i]]
})

constants <- list(n_NAs = n_NAs, NAs = NAs,
                  n_nonNAs = n_nonNAs, nonNAs = nonNAs)

Rmodel <- nimbleModel(code, constants)

Rmodel$A
 [1]  1  2  3  4  5  6  7  8  9 10

Rmodel$B
 [1] 11 12 13 14 15 16 17 18 19 20

Rmodel$x
[1] 11 12 13  4 15  6 17




--
You received this message because you are subscribed to the Google Groups "nimble-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nimble-users...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/nimble-users/C11972BB-B3FB-4ED0-A47F-AEE1581542E8%40biology.nmsu.edu.
Reply all
Reply to author
Forward
0 new messages