繁体   English   中英

R中的向量列表上的foreach

[英]foreach on a list of vectors in R

我有这样的清单

list1<- list(c(12,45,12,0,0),c(12,45,12,0,1),c(14,45,12,0,2),c(12,15,12,0,3),c(12,45,17,0,4))

我想通过在R中使用foreach遍历此列表。这里的目标是将像c(1,1,2,0,6)这样的随机向量与列表中的这些向量进行比较。 通过“比较”,我的意思是我需要计算这些向量之间的欧式距离,并找到与我的随机向量最接近的一个。

使用dist函数可以实现最有效的距离计算方法。

# a random vector
rvec  <- c(1,1,2,0,6)

# a list of coordinates
list1 <- list(c(12,45,12,0,0),
              c(12,45,12,0,1),
              c(14,45,12,0,2),
              c(12,15,12,0,3),
              c(12,45,17,0,4))

# calculate distances between the random vector and the list elements:
dist(rbind(rvec, t(matrix(unlist(list1), length(list1)))))[seq_along(list1)]

[1] 46.82948 46.71188 47.12749 20.63977 47.81213

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM