setwd() works weird inside a function?

I have a function for choosing files using file.choose(). When I call it inside a script I want it open certain directory where I wish to choose files. There is a cycle inside the function as I need to choose a bunch of files. First time it opens in the working directory, which is predictable. I put setwd() inside to make the needed directory as working directory so I can choose files there. But when dialog box opens next time it is again the old working directory. But next time it is the directory I need. If I choose different folders it works the same - next time the old directory but after that the new one. I wrote a short function that reproduces behavior:

foo <- function() {
  files <- NULL
  for (i in c(1,2,3,4,5)) {
    x <- file.choose()
    y <- dirname(x)
    setwd(y)
    print(y)
    print(getwd())
  }

}

Just call this function and try to choose files in different or same directories. You can see that directory name is new and getwd() says that new working directory is set but next file choice dialog opens in previous directory.
Please keep in mind that I need to use file.choose() function as it works on a headless OS, both Windows and Unix-like.
When I don't use setwd() it is always the old working directory.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.