Home > Net >  Replace a for loop with foreach in r
Replace a for loop with foreach in r

Time:04-21

I want to replace the for loop with a foreach loop but I get an error "unexpected token in". Below you can see my code. Just to mention that all the f's are file names. Do you have any idea?

for (f in file) {
  print(f)
  analyze(f)
  tmp <- res4
  y <- rbind(y, tmp)
}

CodePudding user response:

Here is a simple foreach loop using the sequential %do% operator.
Note that the first 2 values of vector file are the output of print.

library(foreach)

file <- c("/data/an_01h.dat", "/data/an_01h.dat")
foreach (f=file) %do% {
  print(f)
}
#> [1] "/data/an_01h.dat"
#> [1] "/data/an_01h.dat"
#> [[1]]
#> [1] "/data/an_01h.dat"
#> 
#> [[2]]
#> [1] "/data/an_01h.dat"

Created on 2022-04-21 by the reprex package (v2.0.1)


And a parallelized loop. The %dopar% operator is a parallelizable operator. This time print doesn't show its output, see this SO question on this.

library(foreach)
library(doParallel)
#> Loading required package: iterators
#> Loading required package: parallel

file <- c("/data/an_01h.dat", "/data/an_01h.dat")

ncores <- detectCores() - 1L
registerDoParallel(ncores)  # use multicore, set to the number of our cores
foreach (f=file) %dopar% {
  print(f)
}
#> [[1]]
#> [1] "/data/an_01h.dat"
#> 
#> [[2]]
#> [1] "/data/an_01h.dat"

Created on 2022-04-21 by the reprex package (v2.0.1)

  • Related