简体   繁体   中英

file.choose() blocks tcltk::tk_choose.files() in R

I asked a similar question today, but wasn't able to get a firm answer. I did get a suggestion to use browser() though.

The code snippet I have is as follows:

library(tcltk)

obs1 <- TRUE
obs2 <- FALSE

if (obs1) {
  if (obs2) {
    file.choose()
 } else {
    file.names <- tk_choose.dir(caption = "Select the folder where files are located")
    for (i in 1:length(file.names)) {
      x <- read.csv(file = file.names[i])
    }
   }
 }

The problem is that the pop-up window called by file.choose() blocks the window called by tk_choose.dir().

Only one window should appear based at any one time on the desired condition above.

I did some investigating and found this old unanswered post on RNabble from a number of years ago:

https://r.789695.n4.nabble.com/Bringing-tk-choose-files-to-front-td4657938.html

and I believe this is the same issue I have.

Any ideas on how to stop R from opening two windows at once?

I may be misunderstanding your problem, but you don't seem to be using the function tk_choose.dir correctly. It returns a string with the directory name, yet you are trying to loop through it as though it is a vector of file names.

The following code runs as expected, launching a single window that allows me to choose a directory, then returns a list of dataframes made of all the csv files in that directory:

x <- list()
if (obs1) {
  if (obs2) {
    file.choose()
 } else {
    Dir <- tk_choose.dir(caption = "Select the folder where files are located")
    file.names <- paste0(Dir, "/", list.files(Dir, pattern = "*.csv"))
    for (i in 1:length(file.names)) 
    {
      x[[i]] <- read.csv(file = file.names[i])
    }
   }
}

which, after picking a directory with a single csv, gives me:

str(x)
List of 1
 $ :'data.frame':   107 obs. of 4 variables:
  ..$ unit          : Factor w/ 2 levels "Barnsley","Sheffield": 2 2 2 2 2 2 2 2 2 2 ...
  ..$ sex           : Factor w/ 2 levels "Female","Male": 2 2 1 2 1 1 2 2 1 1 ...
  ..$ age           : int [1:107] 47 48 19 66 67 83 38 40 84 68 ...
  ..$ arrivals      : Factor w/ 50 levels "2015-10-16 00:00:00",..:

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