假设我们有一个10x5数据集,其中包含10个葡萄酒样品(行)的5个化学测量(例如,var1、var2、var3、var4、var5)。我们想用k均值聚类对葡萄酒样品进行化学测量。这样做很容易。但是,我想要执行连续的聚类,首先使用单个化学测量对葡萄酒样本进行聚类,然后对var1、var2、var3、var4和var5 (所有一元、二进制、三元、四元和五元组合)执行聚类操作。
换句话说,我对葡萄酒样品进行聚类的兴趣是基于列中所有可能的组合,这将导致总共31种聚类结果,例如基于(1)var1、(2)var2、(3)var3、(4)var4、(5)var5、(6)var1和var2、(7)var1和var3、.、.var1、var2、var3、var4和var5。
我如何在R中创建这样一个循环?
发布于 2015-03-25 14:56:34
假设您有一个数据集:
set.seed(144)
dat <- matrix(rnorm(100), ncol=5)现在,您可以获得所有列的子集(由逻辑向量指示是否保留每一列),删除第一列(这将删除所有列)。
(cols <- do.call(expand.grid, rep(list(c(F, T)), ncol(dat)))[-1,])
# Var1 Var2 Var3 Var4 Var5
# 2 TRUE FALSE FALSE FALSE FALSE
# 3 FALSE TRUE FALSE FALSE FALSE
# 4 TRUE TRUE FALSE FALSE FALSE
# ...
# 31 FALSE TRUE TRUE TRUE TRUE
# 32 TRUE TRUE TRUE TRUE TRUE最后一步是对列的每个子集运行k均值集群,这是apply的一个简单应用程序(假设您希望在每个模型中包含3个集群):
mods <- apply(cols, 1, function(x) kmeans(dat[,x], 3))您可以使用列表索引访问您的31k均值模型中的每一个。例如:
mods[[1]]
# K-means clustering with 3 clusters of sizes 7, 5, 8
#
# Cluster means:
# [,1]
# 1 -1.4039782
# 2 -0.4215221
# 3 0.3227336
#
# Clustering vector:
# [1] 1 3 2 1 1 3 3 1 3 3 2 3 2 1 3 3 2 1 1 2
#
# Within cluster sum of squares by cluster:
# [1] 0.4061644 0.1438443 0.7054191
# (between_SS / total_SS = 89.9 %)
#
# Available components:
#
# [1] "cluster" "centers" "totss" "withinss" "tot.withinss" "betweenss"
# [7] "size" "iter" "ifault" 发布于 2015-03-25 14:58:22
# create a dummy matrix
dummy <- matrix(rnorm(10 * 5), 10, 5)
# create all the combinations of variables
combos <- lapply(1:5, function(x) t(combn(1:5, x)))
# loop over the combination sets and fit a k-means with 2 clusters to each
kms <- lapply(combos, function(x) {
lapply(1:nrow(x), function(y) {
kmeans(dummy[,x[y,]], 2)
})
})
> sapply(kms, length)
[1] 5 10 10 5 1
# access the results like so:
> kms[[1]][[1]]
K-means clustering with 2 clusters of sizes 3, 7
...https://stackoverflow.com/questions/29258430
复制相似问题