Learn R Programming

nimble (version 1.2.1)

declare: Explicitly declare a variable in run-time code of a nimbleFunction

Description

Explicitly declare a variable in run-time code of a nimbleFunction, for cases when its dimensions cannot be inferred before it is used. Works in R and NIMBLE.

Usage

declare(name, def)

Arguments

name

Name of a variable to declare, without quotes

def

NIMBLE type declaration, of the form TYPE(nDim, sizes), where TYPE is integer, double, or logical, nDim is the number of dimensions, and sizes is an optional vector of sizes concatenated with c. If nDim is omitted, it defaults to 0, indicating a scalar. If sizes are provided, they should not be changed subsequently in the function, including by assignment. Omitting nDim results in a scalar. For logical, only scalar is currently supported.

Author

NIMBLE development team

Details

In a run-time function of a nimbleFunction (either the run function or a function provided in methods when calling nimbleFunction), the dimensionality and numeric type of a variable is inferred when possible from the statement first assigning into it. E.g. A <- B + C infers that A has numeric types, dimensions and sizes taken from B + C. However, if the first appearance of A is e.g. A[i] <- 5, A must have been explicitly declared. In this case, declare(A, double(1)) would make A a 1-dimensional (i.e. vector) double.

When sizes are not set, they can be set by a call to setSize or by assignment to the whole object. Sizes are not automatically extended if assignment is made to elements beyond the current sizes. In compiled nimbleFunctions doing so can cause a segfault and crash the R session.

This part of the NIMBLE language is needed for compilation, but it also runs in R. When run in R, is works by the side effect of creating or modifying name in the calling environment.

Examples

Run this code
declare(A, logical())             ## scalar logical, the only kind allowed
declare(B, integer(2, c(10, 10))) ## 10 x 10 integer matrix
declare(C, double(3))             ## 3-dimensional double array with no sizes set.

Run the code above in your browser using DataLab