Clustering by groups [duplicate]

可紊 提交于 2019-12-11 05:00:29

问题


How can I perform clustering by groups? For example, take this Pokemon dataset on Kaggle.

A sample of this dataset looks like this (changed some fields to mimic my data):

Name                        Type I  Type II
Bulbasaur                   Grass   Poison  
Bulbasaur 2                 Grass   Poison  
Venusaur                    Grass   Not Null
VenusaurMega Venusaur       Grass   Not Null
...
Charizard                   Fire    Flying
CharizardMega Charizard X   Fire    Dragon

Supposing there are no nulls in my dataset, how can I group by the Type I and Type II columns respectively, and then cluster by similarity between names?

The output should be like so:

Name                        Type I  Type II  Cluster
Bulbasaur                   Grass   Poison   1
Bulbasaur 2                 Grass   Poison   1
Venusaur                    Grass   Not Null 2
VenusaurMega Venusaur       Grass   Not Null 2
...
Charizard                   Fire    Flying   3
CharizardMega Charizard X   Fire    Dragon   4

I tried a method similar as shown here, but it doesn't work with the NbClust function I am using.

clust <- NbClust(data, diss= string_dist, distance=NULL, min.nc = 2, max.nc = 125, method="ward.D2", index="ch")

回答1:


You can use: rleid from library(data.table).

df <- fread("
#,Name,Type 1,Type 2,Total,HP,Attack,Defense,Sp. Atk,Sp. Def,Speed,Generation,Legendary
1,Bulbasaur,Grass,Poison,318,45,49,49,65,65,45,1,False
      2,Ivysaur,Grass,Poison,405,60,62,63,80,80,60,1,False
      3,Venusaur,Grass,Poison,525,80,82,83,100,100,80,1,False
      3,VenusaurMega Venusaur,Grass,Poison,625,80,100,123,122,120,80,1,False
      4,Charmander,Fire,,309,39,52,43,60,50,65,1,False
      5,Charmeleon,Fire,,405,58,64,58,80,65,80,1,False
      ")

Edit: (see the comments)

setDT(df, key=c("Type 1","Type 2"))[, Cluster:=.GRP, by = key(df)][]



回答2:


We can use base R

df$cluster <- with(df, match(`Type II`, unique(`Type II`)))


来源:https://stackoverflow.com/questions/44130032/clustering-by-groups

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