Microsoft SQL and R, stored procedure and k-means

五迷三道 提交于 2019-12-05 20:35:44

We can try the following:

CREATE TABLE #tempData (x float not null, y float not null); 
INSERT INTO #tempData   VALUES (0, 0), (0.1, 0.1), (1, 1), (1.1, 1.1);

CREATE TABLE #output (x float, y float, Cluster int); 

INSERT INTO #output
EXECUTE  sp_execute_external_script
                @language = N'R'
              , @script = N'                
                        trained_model <- kmeans(df[, c("x", "y")], 2)
                        df$cluster <- trained_model$cluster
                        '
              , @input_data_1 = N'SELECT * from #tempData'
              , @output_data_1_name = N'df'
              , @input_data_1_name = N'df';

SELECT *
FROM #output

with output:

x   y   Cluster
0   0   1
0.1 0.1 1
1   1   2
1.1 1.1 2

Note that I specified my input- and output data to be df. The defaults are InputDataSet and OutputDataSet.

If you have longer R-scripts: I would recommend writing and testing them in your R enviroment, then keep them in a package and simply load and call these instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!