gpt4 book ai didi

file - R命令行文件对话框?类似于 file.choose

转载 作者:行者123 更新时间:2023-12-01 02:38:39 26 4
gpt4 key购买 nike

是否有任何 R 用户知道 R 中的“打开文件”类型函数?
最好有一个文本界面,例如:

> 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:
而且我可以浏览,直到我选择了我想要的文件。
我知道当前 file.choose ,但是(无论如何在 Linux 上)它只是说“输入文件名:”并接受您输入的任何内容,但不能让您浏览。 (也许在 Windows 上它会显示一个“打开文件”对话框?)。
我愿意打开文件对话框,但宁愿避免为此加载像 RGtk2/tcltk/etc 这样的 GUI 包。
我也可以自己编写上面的文本浏览器,但我想在我尝试重新发明轮子之前,我会询问是否有人知道这样的功能(并且在它起作用之前弄错了很多很多次!)
干杯。
更新
对于基于文本的界面,答案是否定的。但是基于@TylerRinker 的解决方案和@Iterator 的评论,我编写了自己的函数来做到这一点(感谢他们,这比我想象的要容易得多!):
编辑 - 修改默认为 multiple=F通常人们希望选择一个文件。
#' 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)
}
因为我使用 normalizePath,所以它可能会因为符号链接(symbolic link)和“..”而出错。 , .. 但是哦,好吧。

最佳答案

我有一种你想要的东西,我保存在我的 .Rprofile 中。它有一个菜单界面,因为它默认用于查看工作目录。如果您希望将其扩展为从根目录开始并从那里使用菜单,则必须对功能进行大量修改。

该函数仅在菜单中查找 .txt .R 和 .Rnw 文件。

Open <- function(method = menu) {
wd<-getwd()
on.exit(setwd(wd))

x <- dir()
x2 <- subset(x, substring(x, nchar(x) - 1, nchar(x)) == ".R" |
substring(x, nchar(x) - 3, nchar(x)) %in%c(".txt", ".Rnw"))

if (is.numeric(method)) {
x4 <- x2[method]
x5 <- as.character(x4)
file.edit(x5)
} else {
switch(method,
menu = { x3 <- menu(x2)
x4 <- x2[x3]
x5 <- as.character(x4)
file.edit(x5)
},
look = file.edit(file.choose()))
}
}

##########
#Examples
#########
Open()
Open("L")

关于file - R命令行文件对话框?类似于 file.choose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9122600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com