R language scalar function 1
The following example creates a function that returns the total length of all character input columns.
Code
In R AE, the main object that is provided by the user is a function that is referred to as
nz.fun
. It encapsulates the main AE loop and uses the R AE API to receive and
output data. The following example shows the applyop
implementation in R.
nz.fun <- function () {
while(getNext()) {
op <- getInputColumn(0)
X <- c()
for (i in seq(1, inputColumnCount()-1)) {
x <- as.numeric(getInputColumn(i))
if (!is.null(x) && !is.na(x))
X <- append(X, x)
}
if (op != '+' && op != '*')
stop('incorrect operator: ', op)
setOutputInt32(0, eval(parse(text=paste(X, collapse=op))))
outputResult()
}
}
The main loop ends when getNext()
returns false, which indicates that there are
no more input rows to process. Each input row is accessed by the getInputColumn()
that returns the value of the column that is specified by its index. The index of the first column
is zero, and the index of the last column is inputColumnCount()-1
. The output
values are handled by the setOutput*
functions, where the asterisk represents a
specific data type identifier. To send the output values to the database, the
outputResult()
function must be called.
If an error occurs, call the standard R stop()
function, or use the AE API
function named userError()
. Both functions interrupt program execution and return
the error message to the caller.
Compilation
/nz/export/ae/utilities/bin/compile_ae --language r \
--version 3 --template compile --user nz --db dev \
/tmp/applyop.R
During the compilation step, the input source file is serialized by using standard R API and prepared for further execution. The output is stored under a predefined path that is accessible from the Host and on the SPUs, depending on the database and user names.
Registration
- As the template name, udf must be specified.
- User name, database name, and UDX signature including output type must match the compilation values.
- The executable name must match the source file name from the compilation step.
/nz/export/ae/utilities/bin/register_ae --language r \
--version 3 --user nz --db dev --template udf \
--sig 'applyop(VARARGS)' --return INT4 --exe applyop.R
Running
SELECT applyop('+', 4, 10);
APPLYOP
---------
14
(1 row)
SELECT applyop('*', 3, 5);
APPLYOP
---------
15
(1 row)
SELECT applyop('-', 3, 5);
ERROR: Error in function () : incorrect operator: -