我以为我问专家-抱歉,这更像是一个代码审查问题,但我在下面添加了它。以下代码是否可以获取与第一行最接近的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
答案 0 :(得分:4)
将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]
删除了第3列,但是order
仍然为您提供了1到3的值,而不是1,2和4。
答案 1 :(得分:2)
使用@GKi建议将距离矩阵的对角元素设置为NA,
diag(gower_dist) <- NA
我们还可以使用dplyr::top_n
library(dplyr)
n <- 2
row <- 3
example_df %>%
top_n(n, -gower_dist[, row])
# gender age
# 1 male 30.0
# 2 male 30.1