25. Function Setup + Usage
-- Define function
CREATE LIBRARY rlib
AS ‘/path/rcode.R’ LANGUAGE 'R';
CREATE TRANSFORM FUNCTION Kmeans
AS LANGUAGE 'R' NAME 'kmeansCluFactory' LIBRARY rlib;
-- Use function
CREATE TABLE point_data (
x FLOAT, y FLOAT );
SELECT Kmeans(x, y)
OVER() FROM point_data;
R Source Code
UDx in R Example: K-Means Clustering
# Example: K-means (k=5)
# Input: two-dimensional points
# Output: the point coordinates plus their assigned
# cluster
kmeansClu <- function(x)
{
cl <- kmeans(x,5,10)
res <- data.frame(x[,1:2], cl$cluster)
res
}
kmeansCluFactory <- function()
{
list(name=kmeansClu,
udxtype=c("transform"),
intype=c("float","float"),
outtype=c("float","float","int"),
outnames=c(“col1",“col2","cluster") )
}