请原谅标题没有更好的短语来描述我的问题。
我正在运行'flexclust'包中的集群稳定性分析功能,它在您的数据集上运行引导采样,计算每个k的每个值(我指定的范围)称为“随机索引”的东西。
该函数允许您尝试多种距离度量和聚类方法,我想为每个距离和方法组合运行该函数,根据每个 k 的均值 + 中值找到最佳 k。
我基本上已经编写了嵌套的 for 循环,为每一列初始化向量:(名称、距离度量、方法和最佳 k)。并调用 data.frame() 将它们拼接在一起。
###############################################################################################
df = data.frame(matrix(rbinom(10*100, 1, .5), ncol=4)) #random df for testing purpose
cl_stability <- function(df, df.name, k_low, k_high)
{
cluster.distance = c("euclidean","manhattan")
cluster.method = c("kmeans","hardcl","neuralgas")
for (dist in cluster.distance)
{
for (method in cluster.method)
{
j = 1
while (j <= length(cluster.distance)*length(cluster.method))
{
df.names = rep(c(df.name),length(cluster.distance)*length(cluster.method))
distances = c()
methods = c()
best.k.s = c()
ip = as.data.frame((bootFlexclust(df, k = k_low:k_high, multicore = TRUE,
FUN = "cclust", dist = d, method = m))@rand)
best_k = names(which.max(apply(ip, 2, mean) + apply(ip, 2, median))) #this part runs fine when I run them outside of the function
distances[j] = d
methods[j] = m
best.k.s[j] = best_k
j = j + 1
final = data.frame(df.names,distances,methods,best.k.s)
}
}
}
return(final)
}
预期结果将是一个包含 7 列的数据框(名称、距离度量、方法和最佳 k、第二佳、第三佳和基于中值+平均标准的最差。)。