R language scalar function 2
The following function calculates the total length of the character input columns.
Code
Enter the following code in the /tmp/rlength.R
file:
nz.fun <- function () {
while(getNext()) {
s <- 0
for (i in seq(inputColumnCount())) {
x <- getInputColumn(i-1)
if (is.character(x)) {
s <- s + nchar(x)
}
}
if (s == 0) {
stop('no character columns in input')
}
setOutputInt32(0, s)
outputResult()
}
}
Compilation
Compile the code as follows:
/nz/export/ae/utilities/bin/compile_ae --language r \
--version 3 --template compile --user nz --db dev \
/tmp/rlength.RRegistration
To take full advantage of the R code, register the compiled UDAP with the VARARGS input
signature. This signature indicates that the specific function can handle any number of arguments of
arbitrary types:
/nz/export/ae/utilities/bin/register_ae --language r \
--version 3 --user nz --db dev --template udf \
--sig 'rlength(VARARGS)' --return INT4 --exe rlength.RIn these examples the user is specified as nz, which is an example user ID. The
value that you use should be a valid database user name.
Running
When you run this function, you get the following
result:
SELECT rlength('sample text');
RLENGTH
---------
11
(1 row)
When you run this function for a table
iris, which is a copy of the standard R
iris data set you get the following
result:SELECT rlength(SPECIES) FROM iris;
RLENGTH
---------
6
6
6
(147 more rows)
The following example shows the use of the VARARGS input
signature:
SELECT rlength('sample text',1, 'another text',2,3,4,'and one more text');
RLENGTH
---------
40
(1 row)