通过 2 个变量对许多数据集 R 进行聚类

Clustering many datasets R by 2 variables

我有 15 个数据框,它们的结构相似:(id,v1,v2) 我想要的是基于 V1 和 V2 对它们进行聚类

来自 df1 的示例数据:

ID, V1, V2
1, 0.5, 25
2, 0.3, 2

如果我理解你是对的,你想将相似的 data.frames 归为一组。所有这些 data.frames 具有相同的结构,因此您需要 "flatten" 将数据帧输出到向量中:

首先我们模拟看起来像您的数据:

set.seed(100)
d1 <- replicate(10,
data.frame(id=1:2,
V1=rnorm(2,0,1),
V2=rnorm(2,0,1)),
simplify=FALSE)
names(d1) = paste("df",1:10,sep="")

d2 <- replicate(5,
data.frame(id=1:2,
V1=rnorm(2,3,1),
V2=rnorm(2,3,1)),
simplify=FALSE)
names(d2) = paste("df",11:15,sep="")

alldataframes = c(d1,d2)

我将所有 15 个数据框保存在一个列表中。前 10 个 (df1-10) 与后 5 个 (df11-15) 有不同的分布。首先我们展平:

df_matrix = t(sapply(alldataframes,function(i)unlist(i[,-1])))

现在你有一个矩阵,每一行对应一个 data.frame,每一列,你的 data.frame 中的一个单元格。

head(df_matrix)
           V11        V12         V21         V22
df1 -0.5021924  0.1315312 -0.07891709  0.88678481
df2  0.1169713  0.3186301 -0.58179068  0.71453271
df3 -0.8252594 -0.3598621  0.08988614  0.09627446
df4 -0.2016340  0.7398405  0.12337950 -0.02931671

你可以在此基础上进行聚类,例如 kmeans:

kmeans(df_matrix,2)
K-means clustering with 2 clusters of sizes 5, 10

Cluster means:
         V11       V12        V21       V22
1  2.6399811 3.9138233  2.3044190 3.0689895
2 -0.4166189 0.2219812 -0.1535242 0.7488705

Clustering vector:
 df1  df2  df3  df4  df5  df6  df7  df8  df9 df10 df11 df12 df13 df14 df15 
   2    2    2    2    2    2    2    2    2    2    1    1    1    1    1 

Within cluster sum of squares by cluster:
[1] 26.55861 12.17958
 (between_SS / total_SS =  74.7 %)

Available components:

[1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
[6] "betweenss"    "size"         "iter"         "ifault"