Search code examples
rerror-handlingsyntax-errork-meanssom

How to solve error: "Error in storage.mode(x) <- "double" : 'list' object cannot be coerced to type 'double'" and get results


I'm trying to run some and k means analysis. But I can't solve it because there's an error code.

Error in storage.mode(x) <- "double" : 'list' object cannot be coerced to type 'double'

library(kohonen)

cdata <- read.delim("Cluster.txt", stringsAsFactors=FALSE)

cdata.n <- scale(subset(cdata, select=-c(ID)))

som_model2 <- supersom(data = cdata.n, grid = somgrid(10, 10, "rectangular"))

k = 6

somClusters <- kmeans(som_model2$codes, centers = 6)

I was advised to use the "unlist", and its result is as follow.

Cluster means:
        [,1]
1 -0.6702128
2  5.2157179
3  1.2555768
4 -0.2632253
5  2.6067733
6  0.3503127

But the results of the example are as follows.

## Cluster means:
##   MONEY     VISIT     CROSS       API
## 1 8.2237320 4.8942046 3.6120212 -0.8606384
## 2 -0.2699493 -0.3223770 -0.3357094 -0.2496793
## 3 0.3566740 0.5408914 0.9180064 -0.6252556
## 4 -0.4596952 -0.6586599 -0.9624127 4.2828612
## 5 2.0625665 2.6264913 2.0452184 -0.7848548
## 6 -0.4199132 -0.5746073 -0.7785007 1.1355674

How can I get this result?

I use this data:

https://github.com/woosa7/R_DataAnalytics/blob/08ea98289f4def3c4f72d4c10d3767784b42619b/R_DataMining/data/Cluster.txt


Solution

  • You should coerce the object to a matrix or a data frame. From the kmeans() documentation:

    x = numeric matrix of data, or an object that can be coerced to such a matrix (such as a numeric vector or a data frame with all numeric columns)

    somClusters2 <- kmeans(data.frame(som_model2$codes), centers = 6)
    somClusters2 
    
    K-means clustering with 6 clusters of sizes 14, 42, 11, 3, 3, 27
    
    Cluster means:
           MONEY      VISIT      CROSS        API
    1 -0.4217639 -0.5810061 -0.8014610  1.1764434
    2 -0.3080303 -0.3977217 -0.4555428 -0.1649521
    3  1.1239411  1.6704112  1.6129638 -0.7312019
    4 -0.4606414 -0.6480549 -0.9548480  3.5595079
    5  5.1169992  3.9174431  2.7584212 -0.8306366
    6  0.1443774  0.2317915  0.5778101 -0.5416495