nimble (version 0.7.0)

nimbleRcall: Make an R function callable from compiled nimbleFunctions (including nimbleModels).

Description

Normally compiled nimbleFunctions call other compiled nimbleFunctions. nimbleRcall enables any R function (with viable argument types and return values) to be called (and evaluated in R) from compiled nimbleFunctions.

Usage

nimbleRcall(prototype, returnType, Rfun, envir = .GlobalEnv)

Arguments

prototype

Argument type information for Rfun. This can be provided as an R function using nimbleFunction type declarations or as a list of nimbleType objects.

returnType

Return object type information. This can be provided similarly to prototype as either a nimbleFunction type declaration or as a nimbleType object. In the latter case, the name will be ignored. If there is no return value this should be void().

Rfun

The name of an R function to be called from compiled nimbleFunctions.

envir

The environment where the nimbleFunction wrapping the call to Rfun should be created.

Value

A nimbleFunction that wraps a call to Rfun with type-declared arguments and return object.

Details

The nimbleFunction returned by nimbleRcall can be used in other nimbleFunctions. When called from a compiled nimbleFunction (including from a model), arguments will be copied according to the declared types, the function named by Rfun will be called, and the returned object will be copied if necessary. The example below shows use of an R function in a compiled nimbleModel.

A nimbleFunction returned by nimbleRcall can only be used in a compiled nimbleFunction. Rfun itself should work in an uncompiled nimbleFunction.

See Also

nimbleExternalCall for calling externally provided C (or other) compiled code.

Examples

Run this code
# NOT RUN {
## Say we want an R function that adds 2 to every value in a vector
add2 <- function(x) {
   x + 2 
}
Radd2 <- nimbleRcall(function(x = double(1)){}, Rfun = 'add2',
returnType = double(1), envir = .GlobalEnv)
demoCode <- nimbleCode({
    for(i in 1:4) {x[i] ~ dnorm(0,1)} 
    z[1:4] <- Radd2(x[1:4])
})
demoModel <- nimbleModel(demoCode, inits = list(x = rnorm(4)),
check = FALSE, calculate = FALSE)
CdemoModel <- compileNimble(demoModel)
# }

Run the code above in your browser using DataLab