0

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)
}
les2004
  • 105
  • 7
  • 1
    The example code is not reproducible, `file`, `y` and `res4` are missing. And so is function `analyze`. Can you give a simple yet reproducible example, say, with a dummy function `analyze<- function(x) {sum(x)}` or something like that, simple? – Rui Barradas Apr 21 '22 at 09:06
  • r doesn't have a foreach statement, are you using the foreach package? – George Savva Apr 21 '22 at 09:08
  • Suppose file = c("/data/an_01h.dat", "/data/an_01h.dat"). How can I run a simple forech? for (f in file) { print(f) } – les2004 Apr 21 '22 at 09:10
  • Yes I use the foreach package – les2004 Apr 21 '22 at 09:10
  • 2
    The error you received is a syntax error for the code you haven't shown us. You should post code that reproduces the error you saw. – user2554330 Apr 21 '22 at 10:48

1 Answers1

2

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)

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66