2012-11-26 22 views
-1

名单上我有这样的foreach载体中的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)这些列表中的向量。通过“比较”,我的意思是我需要计算这些向量之间的欧氏距离并找到最接近我的随机向量的距离。

+0

你有什么试过的?你为什么要使用'foreach'而不是'lapply'及其亲戚? – Roland

回答

2

使用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 
+0

比t(矩阵...':'do.call(rbind,list1)''短。 – A5C1D2H2I1M1N2O1R2T1