lig*_*ang 2 loops for-loop r matrix apply
我是使用apply/purrr函数的新手.我不知道何时以及如何使用此功能.我有矩阵的双循环,我想避免它们.有一种方法可以做到吗?我必须做这个操作(见下面的代码)
NCols=4
NRows=4
set.seed(1234)
myMat<-matrix(runif(NCols*NRows), ncol=NCols)
myMat
norm=matrix(0,NRows,NCols)
for (i in 1:nrow(myMat)){
for (j in 1:nrow(myMat)){
norm[i,j] <- sum((myMat[i,]-myMat[j,])^2)
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
对@markus使用dist函数它是更快的方法.
尝试dist看起来你试图计算欧氏距离的平方.
dist(myMat, diag = TRUE, upper = TRUE) ^ 2
# 1 2 3 4
#1 0.0000000 0.7408859 0.9713548 0.9768185
#2 0.7408859 0.0000000 0.8285694 0.1746331
#3 0.9713548 0.8285694 0.0000000 0.3690422
#4 0.9768185 0.1746331 0.3690422 0.0000000
Run Code Online (Sandbox Code Playgroud)