Are there any R users aware of an "open file"-type function in R?
Preferably it’d have a text interface, e.g.:
> file.choose("/path/to/start/at")
path/to/start/at:
[1] [D] a_directory
[2] [D] another_directory
[3] [F] apicture.tif
[4] [F] atextfile.txt
...
[..] Go up a directory
Enter selection:
And I’d be able to browse through until I select the file(s) I wanted.
I am aware of the current file.choose, but (on Linux anyway) that just says "enter file name:" and takes whatever you type in, but doesn’t give you the ability to browse. (Perhaps on Windows it shows an "open file" dialog?).
I’m amenable to an open file dialog but would prefer to stay away from loading a GUI package like RGtk2/tcltk/etc just for this.
I could also write the above text browser myself but I figured I’d ask to see if anyone knew of such a function before I try to reinvent the wheel (and get it wrong many, many, times before it works!)
cheers.
Update
The answer is "no" to the text-based interface. But based on @TylerRinker’s solution and comments by @Iterator, I wrote my own function to do it (and it was much easier than I thought thanks to them!):
Edit – modified default to multiple=F as usually people expect to select one file.
#' Text-based interactive file selection.
#'@param root the root directory to explore
#' (default current working directory)
#'@param multiple boolean specifying whether to allow
#' multiple files to be selected
#'@return character vector of selected files.
#'@examples
#'fileList <- my.file.browse()
my.file.browse <- function (root=getwd(), multiple=F) {
# .. and list.files(root)
x <- c( dirname(normalizePath(root)), list.files(root,full.names=T) )
isdir <- file.info(x)$isdir
obj <- sort(isdir,index.return=T,decreasing=T)
isdir <- obj$x
x <- x[obj$ix]
lbls <- sprintf('%s%s',basename(x),ifelse(isdir,'/',''))
lbls[1] <- sprintf('../ (%s)', basename(x[1]))
files <- c()
sel = -1
while ( TRUE ) {
sel <- menu(lbls,title=sprintf('Select file(s) (0 to quit) in folder %s:',root))
if (sel == 0 )
break
if (isdir[sel]) {
# directory, browse further
files <- c(files, my.file.browse( x[sel], multiple ))
break
} else {
# file, add to list
files <- c(files,x[sel])
if ( !multiple )
break
# remove selected file from choices
lbls <- lbls[-sel]
x <- x[-sel]
isdir <- isdir[-sel]
}
}
return(files)
}
It might barf with symlinks and the ‘..’ since I use normalizePath, .. but oh well.
I have kind of what you want made that I keep in my .Rprofile. It has a menu interface as it’s default for looking through the working directory. If you want it extended to start with he root directory and work out with menus from there you’d have to do a lot of modifying of the function.
The function finds only .txt .R and .Rnw files in the menu.