根据R中的簇聚合有序和二进制数据

时间:2014-11-06 20:36:07

标签: r aggregate cluster-analysis r-daisy

我使用带有R的CRAN cluster包进行了k-medoid聚类分析。数据位于名为df4 data.frame的13111 obs上。 11个二进制和序数值。在群集之后,我将群集结果应用于原始data.frame,将相应的群集编号显示为用户ID。

如何根据群集聚合二元和序数选项?

例如,Gender变量有男/女值,Age范围从“18-20”,“21-24”,“25-34”,“35-44”,“ 45-54“,”55-64“和”65+“。我希望变量GenderAge中的类别的每个群集的男性和女性值的总和。

这是我的data.frame的头部,带有集群标签列:

#12 variables because I added the clustering object to the data.frame
#I only included two variables from the R output
> str(df4)
'data.frame':   13111 obs. of  12 variables:
 $ Age                  : Factor w/ 7 levels "18-20","21-24",..: 6 6 6 6 7 6 5 7 6 3 ...
 $ Gender            : Factor w/ 2 levels "Female","Male": 1 1 2 2 2 1 2 1 2 2 …

#I only included three variables from the R output
> head(df4)
     Age    Gender   
1   55-64 Female          
2   55-64 Female          
3   55-64   Male          
4   55-64   Male          
5     65+   Male          
6  55-64 Female           

这是一个类似于我的数据集的可重现的例子:

age <- c("18-20", "21-24", "25-34", "35-44", "45-54", "55-64", "65+")
gender <- c("Female", "Female", "Male", "Male", "Male", "Male", "Female")
smalldf <- data.frame(age, gender)
#Import cluster package
library(cluster)
#Create dissimilarity matrix
#Gower coefficient for finding distance between mixed variable
smalldaisy4 <- daisy(smalldf, metric = "gower", 
                     type = list(symm = c(2), ordratio = c(1))) 
#Set randomization seed
set.seed(1)
#Pam algorithm with 3 clusters 
smallk4answers <- pam(smalldaisy4, 3, diss = TRUE)
#Apply cluster IDs to original data frame
smalldf$cluster <- smallk4answers$cluster

期望的输出结果(假设):

  cluster female male 18-20 21-24 25-34 35-44 45-54 55-64 65+
1 1       1      1    1     2     1     0     3     1     0
2 2       2      1    1     1     0     1     2     0     0
3 3       0      1    1     1     1     1     0     2     3

如果我能提供更多信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

看起来您希望在一个矩阵中显示来自逐个性别和逐个群体的表格中的两个表:

 with( smalldf, cbind(table(cluster, gender), table(cluster, age)  ) )
#----------------
  Female Male 18-20 21-24 25-34 35-44 45-54 55-64 65+
1      2    0     1     1     0     0     0     0   0
2      0    4     0     0     1     1     1     1   0
3      1    0     0     0     0     0     0     0   1