#we compare with the sliouette function ############## set.seed(451) data=rbind(matrix(runif(20,1,5), nrow = 2, ncol = 10),matrix(runif(20,20,30), nrow = 2, ncol = 10),matrix(runif(20,50,70), nrow = 2, ncol = 10)) k=3 seed=5 distance<- function(vect1, vect2){ sqrt(sum((vect1-vect2)^2)) } centers_function<-function(data, grouping){ center=matrix(0,length(grouping), dim(data)[2]) for (i in 1:(length(grouping))){ if(length(grouping[[i]])==1){ center[i,]=data[grouping[[i]],] }else{ center[i,]=apply(data[grouping[[i]],],2,mean) } } return(center) } init_centers=init_centers_random #with kmeans if(!is.null(seed)){ set.seed(seed) } centers <- data[sample(1:nrow(data), k), ] kmeas_R=kmeans(data,centers, 10, algorithm ="Hartigan-Wong") dimnames(kmeas_R$centers) <- NULL #With our function FHW_output=Hartigan_and_Wong(data, distance,k,centers_function,init_centers , seed=seed, 10) Ous=Silhouette(data, FHW_output, distance) Rs=cluster::silhouette(kmeas_R$cluster, dist(data)) #We make sure they are the same test_that("Silhouette", { expect_equal(Ous, Rs[,3],tolerance=1e-6) })