【问题标题】:R - How to apply a function with all the possible values for a specified argument?R - 如何应用具有指定参数的所有可能值的函数?
【发布时间】:2019-10-07 22:23:20
【问题描述】:

我想将 kmeans 函数应用于数据集。

我运行了几次。我每次都增加中心的数量。对于每次运行,我将平方和内的总和存储在一个向量中,然后将平方和内的总和与簇的数量作图,如下所示:

# Dummy data
cluster1_x <- rnorm(1000, mean = 3.5, sd = .75)
cluster1_y <- rnorm(1000, mean = 4, sd = 1.13)
cluster1 <- cbind(cluster1_x, cluster1_y)

cluster2_x <- rnorm(1000, mean = 5.2, sd = .75)
cluster2_y <- rnorm(1000, mean = .9, sd = .64)
cluster2 <- cbind(cluster2_x, cluster2_y)

cluster3_x <- rnorm(1000, mean = .68, sd = .86)
cluster3_y <- rnorm(1000, mean = 0.8, sd = 1)
cluster3 <- cbind(cluster3_x, cluster3_y)

df <- rbind(cluster1, cluster2, cluster3)

# To see the dummy clusters
# plot(df, pch = 20) 

# Applying kmeans

# Vector that will be filled with the variance in the clusters
tot.within.sum.square <- rep(NA, 20)

for (nb_center in 1:20){
  tps_start <- Sys.time()
  set.seed(13)
  res.kmeans <- kmeans(df, centers=nb_center, iter.max = 30)
  tot.within.sum.square[nb_center] <- res.kmeans$tot.withinss
  tps_exec <- Sys.time() - tps_start
  print(paste0("Iteration ", nb_center, " : ", tps_exec))
}

plot(1:20, tot.within.sum.square, type = 'b', pch=20)

我想重复这个过程 4 次,每次都使用不同的算法。有 4 个不同的值“Hartigan-Wong”、“Lloyd”、“Forgy”、“MacQueen”,所以我想得到 4 个长度为 20 的不同向量,每个算法一个向量。给定向量的每个元素都是包含在res.kmeans$tot.withinss 中的值。例如,向量的第 4 个元素是对应于 4 个中心的一系列 kmeans 的平方和内的总和。我可以复制并粘贴之前的代码,但我正在寻找一种更优雅的方式来实现结果。

我可以用这个得到我想要的东西:

sapply(algos, function(x) {
  sapply(nb_centers, function(y) kmeans(df, centers = y, algorithm = x))
})

但我无法将每个算法的每次迭代中的每个 total.withinss 存储在一个变量中。

任何帮助将不胜感激!

【问题讨论】:

  • 你快到了:res &lt;- lapply(algos, function(x) { lapply(nb_centers, function(y) kmeans(df, centers = y, algorithm = x)) }); sapply(res, sapply, `[[`, "tot.withinss")
  • 为什么不在内部sapply 调用:kmeans(df, centers = y, algorithm = x)$tot.withinss
  • 谢谢!它就像一个魅力,完美!

标签: r loops apply


【解决方案1】:

正如@Parfait 在 cmets 中提到的,

tot.withinss <- sapply(algos, function(x) {
  sapply(nb_centers, function(y) kmeans(df, centers = y, algorithm = x)$tot.withinss)
})

会成功的!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2011-11-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多