Krish
Krish

Reputation: 70

How to Format Table

I'm currently studying R and got problem in displaying table as in required format.

> p <- rpois(100,5)
> cluster_p <- kmeans(p,3)
> table(cluster_p$cluster)

 1  2  3 
36  4 60 
> table(cluster_p$centers,table(cluster_p$cluster))

                   4 36 60
  3.43333333333333 0  0  1
  6.77777777777778 0  1  0
  9.5              1  0  0

But I have to display table as in format given below.

cluster_id | center | total_no
1           6.77       36
2           9.5        4
3           3.43       60  

How can I achieve this?

Upvotes: 0

Views: 1233

Answers (1)

Nishanth
Nishanth

Reputation: 7130

Just create a data frame:

cluster = as.data.frame(table(cluster_p$cluster))

data.frame(cluster_id=cluster[,1],
           center=cluster_p$centers,
           total_no=cluster[,2])

##   cluster_id   center total_no
## 1          1 3.020408       49
## 2          2 8.700000       10
## 3          3 5.731707       41

ps: table entries are different because you have not set the seed in your example.

Upvotes: 2

Related Questions