简体   繁体   中英

foreach on a list of vectors in R

I have a list like this

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))

I want to iterate through this list by using foreach in R. The goal here is to compare a random vector like c(1,1,2,0,6) with these vectors in the list. By "compare", I mean I need to calculate the euclidean distance between these vectors and find the closest one to my random vector.

The most efficient approach to calculate the distances could be achieved with the dist function.

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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