R - 组内聚类(K-means)

R - Clustering (K-means) within groups

我需要帮助将我的数据聚类到指定的组中...

我有以下数据框:

# Generate data frame
set.seed(1)
df1 <- data.frame(
  start.x = sample(1:20),
  start.y = sample(1:20),
  end.x = sample(1:20),
  end.y = sample(1:20)
)

我用 K-means 对它进行了分组:

# Group using K-means
groups <- kmeans(df1[,c('start.x', 'start.y', 'end.x', 'end.y')], 4)
df1$group <- as.factor(groups$cluster)

现在我想再次使用 K-means 将其聚类到我刚刚创建的组中,并将结果分配给数据框中的新列。

有谁知道如何做到这一点或有更短的方法来同时完成这两个步骤。

谢谢...

我们可以使用第一组来拆分数据并仅将 kmeans 应用于数据子集。不过请确保使用正确数量的 k,因为这取决于第一个组的创建方式。

library(dplyr)
library(purrr)

df1 %>%
  group_split(group = kmeans(.[,c('start.x', 'start.y', 'end.x', 'end.y')], 
                             4)$cluster) %>%
   map_df(~.x %>% mutate(new_group = 
     kmeans(.x[,c('start.x', 'start.y', 'end.x', 'end.y')], 2)$cluster))

在基础 R 中,您可以使用 by 进行拆分、应用和组合操作。

df1$new_group <- unlist(by(df1, df1$group, function(x) 
        kmeans(x[,c('start.x', 'start.y', 'end.x', 'end.y')], 2)$cluster))