R - 如何从异质矩阵中找到最近的邻域?

问题描述 投票:1回答:1

我有一个异同矩阵(gower.dist),现在我想找到离某个数据点(例如第50行)最近的n个邻居。谁能帮助我?

样本数据https:/towardsdatascience.comhierarchical-clustering-on-categorical-data-in-r-a27e578f2995。

#----- Dummy Data -----#
library(dplyr)
set.seed(40)
id.s <- c(1:200) %>%
        factor()
budget.s <- sample(c("small", "med", "large"), 200, replace = T) %>%
            factor(levels=c("small", "med", "large"), 
            ordered = TRUE)
origins.s <- sample(c("x", "y", "z"), 200, replace = T, 
             prob = c(0.7, 0.15, 0.15))
area.s <- sample(c("area1", "area2", "area3", "area4"), 200, 
          replace = T,
          prob = c(0.3, 0.1, 0.5, 0.2))
source.s <- sample(c("facebook", "email", "link", "app"), 200,   
            replace = T,
            prob = c(0.1,0.2, 0.3, 0.4))
dow.s <- sample(c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), 200, replace = T,
         prob = c(0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.2)) %>%
         factor(levels=c("mon", "tue", "wed", "thu", "fri", "sat", "sun"), 
        ordered = TRUE)
dish.s <- sample(c("delicious", "the one you don't like", "pizza"), 200, replace = T)

synthetic.customers <- data.frame(id.s, budget.s, origins.s, area.s, source.s, dow.s, dish.s)

#----- Dissimilarity Matrix -----#
library(cluster) 
# to perform different types of hierarchical clustering
# package functions used: daisy(), diana(), clusplot()
gower.dist <- daisy(synthetic.customers[ ,2:7], metric = c("gower"))
r cluster-analysis hierarchical-clustering
1个回答
2
投票

假设你想找离50号数据点最近的5个邻域。

row_number <- 50
n <- 5

dists <- unname(as.matrix(gower.dist)[row_number,])
order(dists)[1:n]

# 50  83 112  60  75

事实上,50号是离自己最近的,其余的是4个最近的值。"技巧 "是将你的对象转换为矩阵,提取你感兴趣的行,并使用基础的R order 函数来查找该行中最小值的指数。

© www.soinside.com 2019 - 2024. All rights reserved.