我们可以使用fields 包中的rdist 来计算test 中的每一行与truth 中的每一行之间的欧几里得距离矩阵。首先是数据:
set.seed(123) ## for reproducibility
D <- 2 #amount of dimensions
K <- 5
events <- 2*K #number of events
truth <- matrix(data=runif(events, min = 0, max = 1), nrow=K)
## [,1] [,2]
##[1,] 0.2875775 0.0455565
##[2,] 0.7883051 0.5281055
##[3,] 0.4089769 0.8924190
##[4,] 0.8830174 0.5514350
##[5,] 0.9404673 0.4566147
E <- 2
test <- matrix(data=runif(2*E, min = 0, max = 1), nrow=E)
## [,1] [,2]
##[1,] 0.9568333 0.6775706
##[2,] 0.4533342 0.5726334
使用rdist计算距离矩阵:
library(fields)
d <- rdist(test,truth)
## [,1] [,2] [,3] [,4] [,5]
##[1,] 0.9205136 0.2252589 0.5884781 0.1461471 0.2215612
##[2,] 0.5525263 0.3379176 0.3228474 0.4302058 0.5007584
要找到最接近每个test 行的truth 行,apply which.min 与MARGIN=1 的行重叠:
apply(d,1,which.min)
##[1] 4 3