Reputation: 17418
I am trying to use the distances package with code along those lines:
library(distances)
library(dplyr)
set.seed(42)
x <- matrix(rnorm(100), ncol = 10)
df <- as.data.frame(x)
df$id <- paste0("x_", seq.int(nrow(df)))
distances <- distances(df, id_variable = "id")
distances
This produces a distances matrix object like this:
x_1 x_2 x_3 x_4 x_5 x_6 x_7 x_8 x_9 x_10
x_1 0.000000 3.843183 4.093911 3.643060 4.935399 4.327867 4.287775 6.205355 6.197274 2.180997
x_2 3.843183 0.000000 5.084690 5.170822 5.067423 3.788407 4.383991 5.770031 7.113060 2.830447
x_3 4.093911 5.084690 0.000000 3.571286 4.547878 4.102882 3.531970 3.916854 6.470266 3.733713
x_4 3.643060 5.170822 3.571286 0.000000 3.820931 3.842954 3.667172 5.513104 5.176213 3.294032
x_5 4.935399 5.067423 4.547878 3.820931 0.000000 4.815130 3.465038 5.917983 6.137555 4.763992
x_6 4.327867 3.788407 4.102882 3.842954 4.815130 0.000000 2.793542 3.936627 5.475425 3.022680
x_7 4.287775 4.383991 3.531970 3.667172 3.465038 2.793542 0.000000 4.075392 5.251397 4.010323
x_8 6.205355 5.770031 3.916854 5.513104 5.917983 3.936627 4.075392 0.000000 5.510953 5.151613
x_9 6.197274 7.113060 6.470266 5.176213 6.137555 5.475425 5.251397 5.510953 0.000000 6.167744
x_10 2.180997 2.830447 3.733713 3.294032 4.763992 3.022680 4.010323 5.151613 6.167744 0.000000
I would like to use the nearest_neighbor_search function of this package to get the closest 3 rows for each row (ideally except the row itself). I read the documentation but am not 100% sure how to use it. Thanks.
So for the first row X_1 this code:
x <- as.data.frame(distance_columns(distances, 1))
x <- tibble::rownames_to_column(x, "id")
x <- x[order(-x[, 2], decreasing = TRUE),]
x
produces:
id x_1
1 x_1 0.000000
10 x_10 2.180997
4 x_4 3.643060
2 x_2 3.843183
3 x_3 4.093911
7 x_7 4.287775
6 x_6 4.327867
5 x_5 4.935399
9 x_9 6.197274
8 x_8 6.205355
The top 3 closest rows would be x_10, x_4 and x_2.
Upvotes: 0
Views: 47
Reputation: 2829
By just writing nearest_neighbor_search(distances, k= 4)
where k is the number of nearest neighbours counting itself (e.g. if you want 3 then you should write 4):
nearest_neighbor_search(distances, 4, query_indices = NULL,
search_indices = NULL, radius = NULL)
x_1 x_2 x_3 x_4 x_5 x_6 x_7 x_8 x_9 x_10
[1,] 1 2 3 4 5 6 7 8 9 10
[2,] 10 10 7 10 7 7 6 3 4 1
[3,] 4 6 4 3 4 10 5 6 7 2
[4,] 2 1 10 1 3 2 3 7 6 6
you get the 3 nearest neighbors for x_1. That is 1 (itself) 10,4 and 2. You can remove the first one.
Upvotes: 1