Learn R Programming

nimble (version 1.2.1)

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,
  where = getNimbleFunctionEnvironment()
)

Value

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

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.

where

An optional where argument passed to setRefClass for where the reference class definition generated for this nimbleFunction will be stored. This is needed due to R package namespace issues but should never need to be provided by a user.

Author

Perry de Valpine

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
if (FALSE) {
## 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))
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