找到两个矩阵的行之间的最小距离
Find minimum distances between rows of two matrices
我有两个表,X 和 Y,(X 很大,Y 有 9 行,当然是相同的列),我需要找到 X 的每一行与 Y 的每一行之间的最小欧氏距离。
我这样做并且有效:
x<-matrix(c(3,6,3,4,8),nrow=5,ncol=7,byrow = TRUE)
y<-matrix(c(1,4,4,1,9),nrow=5,ncol=7,byrow = TRUE)
unlist(lapply(seq_len(nrow(y)), function(i) min(sqrt(colSums((y[i, ] -t(x))^2))))
现在我需要导出Y(1到9)的哪一行是每一行,这是我的问题,因为我不知道如何面对这个。关于如何写这个的任何线索?
我一直在考虑做类似的事情:
unlist(lapply(seq_len(nrow(y)), function(i) nrow(min(sqrt(colSums((y[i, ] - t(x))^2)))==T)))
但我做不到。
谢谢!
您可以使用我的 imputation 包轻松完成此操作:
Sys.setenv("PKG_CXXFLAGS"="-std=c++0x") # needed for the lambda functions in Rcpp
# install/load package, create example data
devtools::install_github("alexwhitworth/imputation")
library(imputation)
set.seed(123)
a <- matrix(rnorm(10000), ncol= 10)
b <- matrix(rnorm(100), ncol=10)
# which row of a is closest to each row of b
apply(b, 1, function(i, a) {
which.min(imputation:::dist_q.matrix(rbind(i, a), ref= 1L, q=2))
}, a= a)
[1] 471 502 555 969 692 757 116 913 556 566
# which row of b is closest to each row of a
apply(a, 1, function(i, b) {
which.min(imputation:::dist_q.matrix(rbind(i, b), ref= 1L, q=2))
}, b= b)
### result not shown since it's large
从技术上讲,您不需要参数 ref
和 q
,因为 1L
和 2
是默认值。
我有两个表,X 和 Y,(X 很大,Y 有 9 行,当然是相同的列),我需要找到 X 的每一行与 Y 的每一行之间的最小欧氏距离。 我这样做并且有效:
x<-matrix(c(3,6,3,4,8),nrow=5,ncol=7,byrow = TRUE)
y<-matrix(c(1,4,4,1,9),nrow=5,ncol=7,byrow = TRUE)
unlist(lapply(seq_len(nrow(y)), function(i) min(sqrt(colSums((y[i, ] -t(x))^2))))
现在我需要导出Y(1到9)的哪一行是每一行,这是我的问题,因为我不知道如何面对这个。关于如何写这个的任何线索? 我一直在考虑做类似的事情:
unlist(lapply(seq_len(nrow(y)), function(i) nrow(min(sqrt(colSums((y[i, ] - t(x))^2)))==T)))
但我做不到。
谢谢!
您可以使用我的 imputation 包轻松完成此操作:
Sys.setenv("PKG_CXXFLAGS"="-std=c++0x") # needed for the lambda functions in Rcpp
# install/load package, create example data
devtools::install_github("alexwhitworth/imputation")
library(imputation)
set.seed(123)
a <- matrix(rnorm(10000), ncol= 10)
b <- matrix(rnorm(100), ncol=10)
# which row of a is closest to each row of b
apply(b, 1, function(i, a) {
which.min(imputation:::dist_q.matrix(rbind(i, a), ref= 1L, q=2))
}, a= a)
[1] 471 502 555 969 692 757 116 913 556 566
# which row of b is closest to each row of a
apply(a, 1, function(i, b) {
which.min(imputation:::dist_q.matrix(rbind(i, b), ref= 1L, q=2))
}, b= b)
### result not shown since it's large
从技术上讲,您不需要参数 ref
和 q
,因为 1L
和 2
是默认值。