add alternative approach from 2013-01
[synclust.git] / src / adapters / a.kmeansClustering.c
CommitLineData
15d1825d
BA
1#include <R.h>
2#include <Rdefines.h>
3#include "sources/kmeansClustering.h"
4#include <cgds/Vector.h>
5
6// k-means based on a distance matrix (nstart=10, maxiter=100)
7SEXP kmeansWithDistances(
8 SEXP distances_,
9 SEXP K_,
10 SEXP nstart_,
11 SEXP maxiter_
12) {
13 // get scalar arguments
14 int K = INTEGER_VALUE(K_);
15 int nstart = NUMERIC_VALUE(nstart_);
16 int maxiter = INTEGER_VALUE(maxiter_);
17
18 // extract infos from M and get associate pointer
19 SEXP dim = getAttrib(distances_, R_DimSymbol);
20 int n = INTEGER(dim)[0];
21 double* pDistances = REAL(distances_);
22
23 // Main call to core algorithm
24 int* clusters = kmeansWithDistances_core(pDistances, n, K, nstart, maxiter);
25
26 // allocations and recopies to R vector object
27 SEXP bestClusts;
28 PROTECT(bestClusts = allocVector(INTSXP, n));
29 int* pBestClusts = INTEGER(bestClusts);
30 for (int i=0; i<n; i++)
31 pBestClusts[i] = clusters[i] + 1; // add 1 to start labels at 1
32 free(clusters);
33
34 // and return clusters
35 UNPROTECT(1);
36 return bestClusts;
37}