我以为我问专家-抱歉,这更像是一个代码审查问题,但我在下面添加了它。以下代码是否可以获取与第一行最接近的top_n种情况-忽略第一行:

example_df <- data.frame(
                  gender = c("male", "male", "female", "male")
                , age = c(30, 30.1, 20, 31)
              )
example_df

gower_dist <- as.matrix(daisy(example_df, metric = "gower"))
gower_dist

top_n <- 2

# select top 2 closest row indices of row 1
example_df[head(order(gower_dist[-1, 1]), top_n) + 1,]

我试图使它也适用于第三行,但这不起作用:
example_df[head(order(gower_dist[-3, 3]), top_n) + 1,]

任何反馈将不胜感激。谢谢!

PS:

距离指标:
            1           2         3          4
1 0.000000000 0.004545455 0.9545455 0.04545455
2 0.004545455 0.000000000 0.9590909 0.04090909
3 0.954545455 0.959090909 0.0000000 1.00000000
4 0.045454545 0.040909091 1.0000000 0.00000000

最佳答案

diag设置为NA将使子设置更容易。

diag(gower_dist)  <- NA
example_df[head(order(gower_dist[, 1]), top_n),]
#  gender  age
#2   male 30.1
#4   male 31.0

example_df[head(order(gower_dist[, 3]), top_n),]
#  gender  age
#1   male 30.0
#2   male 30.1

您使用gower_dist[-3, 3]删除了col 3,但是order仍然为您提供了1到3的值,而不是1,2和4。

关于r - 使top_n最接近的行与数据帧中的第一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59378274/

10-12 22:38