簡體   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