0

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

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

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

这是我的带有集群标签列的 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

让我知道我是否可以提供更多信息。

4

1 回答 1

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
于 2014-11-06T22:37:53.057 回答