updated based on your comments
I don't see any function that returns the indices of the nearest neighbors in the train data concerning the dprep package (hopefully I don't miss something).
However, what you can do is first calculating a distance matrix using the gower distance (FD package) and then pass this matrix to a k-nearest-neighbors function (the KernelKnn package accepts a distance matrix as input). If you decide to use the KernelKnn package then first install the latest version using devtools::install_github('mlampros/KernelKnn').
# train-data [ "col3" is the response variable, 'stringsAsFactors' by default ]
df1 <- data.frame(col1 = c("a","d","f"), col2 = c(1,3,2), col3 = c("T","F","T"), stringsAsFactors = T)
# test-data
tst1 <- data.frame(col1 = c("f"), col2 = c(2), stringsAsFactors = T)
# rbind train and test data (remove the response variable from df1)
df_all = rbind(df1[, -3], tst1)
# calculate distance matrix
dist_gower = as.matrix(FD::gowdis(df_all))
# use the dist_gower distance matrix as input to the 'distMat.knn.index.dist' function
# additionaly specify which row-index is the test-data observation from the previously 'df_all' data.frame using the 'TEST_indices' parameter
idxs = KernelKnn::distMat.knn.index.dist(dist_gower, TEST_indices = c(4), k = 2, threads = 1, minimize = T)
idxs$test_knn_idx returns the k-nearest-neighbors of the test data observation in the train data
print(idxs)
$test_knn_idx
[,1] [,2]
[1,] 3 1
$test_knn_dist
[,1] [,2]
[1,] 0 0.75
if you want also the probability for the class labels, then first convert to numeric and then use the distMat.KernelKnn function
y_numeric = as.numeric(df1$col3)
labels = KernelKnn::distMat.KernelKnn(dist_gower, TEST_indices = c(4), y = y_numeric, k = 2, regression = F, threads = 1, Levels = sort(unique(y_numeric)), minimize = T)
print(labels)
class_1 class_2
[1,] 0 1
# class_2 corresponds to "T" from col3 (df1 data.frame)
Alternatively, you could take a look to the dprep::knngow and especially the second part of the function which is actually what you are interested in,
> print(dprep::knngow)
....
else {
for (i in 1:ntest) {
tempo = order(StatMatch::gower.dist(test[i, -p], train[, -p]))[1:k]
classes[i] = moda(train[tempo, p])[1]
}
}
.....