【问题标题】:R - Clustering (K-means) within groupsR - 组内的聚类(K-means)
【发布时间】:2020-08-27 17:11:27
【问题描述】:

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

我有以下数据框:

# 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 将它聚集在我刚刚创建的组中,并将结果分配给数据框中的新列。

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

谢谢...

【问题讨论】:

    标签: r dplyr lapply k-means sapply


    【解决方案1】:

    我们可以使用第一组来拆分数据并将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))
    

    【讨论】:

    • 基础 R 实现的启动速度非常快!谢谢
    猜你喜欢
    • 2013-02-07
    • 2018-04-05
    • 2018-02-10
    • 2017-08-18
    • 2015-04-11
    • 2019-03-16
    • 2019-11-18
    • 2011-08-13
    • 2013-08-08
    相关资源
    最近更新 更多