iembry
iembry

Reputation: 944

r - foreach loop not replicating traditional loop

I am in the process of transforming a traditional loop to a foreach loop for solving the shoelace formula problem in R; however, I am not getting the right accumulation with the foreach loop.

   library("foreach")   
   x = c(0, 4, 4, 0)

   # coordinates of points   
   y = c(0, 0, 4, 4)

   # coordinates of points   
   points <- length(x)   
   area <- 0

   # Accumulates area in the loop   
   i <- 0   
   j <- points

   # using foreach loop
   area <- foreach(i = seq(x), .combine = "+") %do% {   
     (x[[j]] + x[[i]]) * (y[[j]] - y[[i]])   
     j <- i   
   }   
   area # 10

This is just 1 + 2 + 3 + 4. It has not taken into account the points in x and y.

   # using traditional loop   
   area <- vector("list", length(x))   
   for (i in seq_along(x)) {   
     area[[i]] <- (x[[j]] + x[[i]]) * (y[[j]] - y[[i]])   
     j <- i   
   }   
   area

   # [[1]]
   # [1] 0   
   # [[2]]
   # [1] 0

   # [[3]]
   # [1] -32

   # [[4]]
   # [1] 0

The sum is 32 units, which is correct.
What am I doing wrong with the foreach loop? Thank you.

Upvotes: 0

Views: 51

Answers (1)

F. Priv&#233;
F. Priv&#233;

Reputation: 11728

foreach is returning the last calculated expression, as in regular functions.

So, you can do:

area <- foreach(i = seq(x)) %do% {
  j0 <- j
  j <- i   
  (x[[j0]] + x[[i]]) * (y[[j0]] - y[[i]])   
}  

Upvotes: 1

Related Questions