【问题标题】:lapply(tk_choose.files) customize file selection windowlapply(tk_choose.files) 自定义文件选择窗口
【发布时间】:2016-07-12 07:20:42
【问题描述】:

我想创建一个弹出的对话窗口,用户将能够选择多个 xlsx 文件并返回数据列表。我发现一个可能的解决方案是使用tk_choose.files,但它给了我一个错误。

choose.dir(getwd(), "Choose a suitable folder")

library(xlsx)
library(rJava)
library(xlsxjars)
library(tcltk)

#get file names
f = list.files("./")

#read files
dat = lapply(f, function(i){
  x = tk_choose.files(caption="Choose your files"), read.xlsx(i, sheetIndex = 1, sheetName = NULL, startRow = 24,
                endRow = NULL, as.data.frame = TRUE, header = FALSE)
  #return columns with names and colors
  x = x[, c(2, 5, 7, 9, 11, 13, 15, 17, 19), drop=FALSE]
  #return the data
  x
})

错误:意外的“,”在: “dat = lapply(f,函数(i){ x = tk_choose.files(caption="选择你的文件"),"

我知道语法有错误,但我对 R 很陌生,不知道如何正确编写。

有人可以帮忙吗?

【问题讨论】:

  • 您要在lapply 中选择带有tk_choose.files 的文件吗?
  • library(rJava)library(xlsxjars) 的调用是多余的,因为library(xlsx) 调用了所有依赖项
  • Uwe Block,是的,这就是我想要做的。不知道图书馆(xlsx),谢谢
  • 如果您想避免未来的头痛,请使用R 赋值运算符&lt;- 而不是模棱两可的=(请参阅Chapter 8.2.26 "= is not a synonym of <-" of Patrick Burns' "The R Inferno")。
  • 我尝试使用&lt;- 而不是=,但我得到了同样的错误

标签: r xlsx lapply filechooser


【解决方案1】:

你可以尝试一下

#read files
dat <- lapply(tk_choose.files(caption="Choose your files"), function(i) {
  x <- read.xlsx(i, sheetIndex = 1, sheetName = NULL, startRow = 24,
                 endRow = NULL, as.data.frame = TRUE, header = FALSE)
  #return columns with names and colors
  x <- x[, c(2, 5, 7, 9, 11, 13, 15, 17, 19), drop = FALSE]
 #return the data
  x
})

这样,用户在通过lapply调用中的文件名向量之前选择文件。

您收到错误是因为一行中有两个语句,用逗号分隔。你的代码:

x = tk_choose.files(caption="Choose your files"), read.xlsx(i, sheetIndex = 1, sheetName = NULL, startRow = 24,
            endRow = NULL, as.data.frame = TRUE, header = FALSE)

第一个语句是

x = tk_choose.files(caption="Choose your files")

将所选文件名分配给变量x。然后你有一个逗号和第二个语句

read.xlsx(i, sheetIndex = 1, sheetName = NULL, startRow = 24,
          endRow = NULL, as.data.frame = TRUE, header = FALSE)

根本不存储其结果。

【讨论】:

  • 行得通,谢谢!还有一个问题:在我返回数据并应用一些函数后,我想将输出返回到自定义目录。当未自定义输出目录时,例如pth &lt;- "C:/Users/Dev/Desktop/test/,我可以看到输出。当我尝试pth &lt;- choose.dir(default = "", caption = "Choose the output path") 时,我什么也看不到。没有错误,但也没有输出。你知道为什么吗?
  • @joasa 不确定您的意思。这是一个全新的问题吗?请输入一个带有最小工作示例的新问题,以便其他人可以重现该问题 - 谢谢。
猜你喜欢
  • 2011-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-09
  • 2012-08-07
相关资源
最近更新 更多