[英]Sum up the results of a loop in R?
I've created this little code and have troubles to sum up the results of the loop. 我已经创建了这个小代码,并且很难总结循环的结果。 Somebody can help me with it? 有人可以帮我吗?
a = array(c(1,1,1,1,1,1,1,2,1,1,1,1,1), dim=c(4,3))
b = array(c(0,0,0,0,0,1), dim=c(2,3))
dist <- array()
for (j in 1:2) {
for (i in 1:4) {
dist <- sqrt (sum ((a[i, ]-b[j, ])^2))
print(dist)
}
}
I get 8 numbers as result, but can only display the last of it 结果是8个数字,但只能显示最后一个
Alternatively, you could use the outer
function (if someone comes up with a better way to vectorize the anonymous function, please feel free to edit) 或者,您可以使用outer
函数(如果有人提出了更好的矢量化匿名函数的方法,请随时进行编辑)
(dist <- outer(1:4, 1:2, FUN = Vectorize(function(x,y)sqrt(sum((a[x,]-b[y,])^2)))))
[,1] [,2]
[1,] 1.732051 1.414214
[2,] 1.732051 1.414214
[3,] 1.732051 1.414214
[4,] 2.449490 2.236068
1:4
is used to index a
, and 1:2
is used to index b
. 1:4
用于索引a
, 1:2
用于索引b
。
You need to fill in your dist
matrix as you go. 您需要随时填写dist
矩阵。
dist <- array(dim=c(4,2))
for (j in 1:2) {
for (i in 1:4) {
dist[i,j] <- sqrt (sum ((a[i,1:3]-b[j,1:3])^2))
}
}
dist
You could also use the inbuilt dist
function and avoid all these nested for loops 您也可以使用内置的dist
函数,避免所有这些嵌套的for循环
dist
calculates the euclidean distance (the default from number of possibilities). dist
计算欧几里得距离(可能性数的默认值)。 This appears to be what you want. 这似乎是您想要的。
See ?dist
for more details 有关详细信息,请参见?dist
# give a and b some rownames
row.names(a) <- paste0('a',1:nrow(a))
row.names(b) <- paste0('b',1:nrow(b))
#combine into one matrix
ab <- rbind(a,b)
# get the distance between the points
distances <- as.matrix(dist(ab))
# subset those you are interested in
distances[row.names(a),row.names(b)]
## b1 b2
## a1 1.732051 1.414214
## a2 1.732051 1.414214
## a3 1.732051 1.414214
## a4 2.449490 2.236068
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.