在R中保存时自动添加扩展名

时间:2017-07-05 14:25:27

标签: r

我正在使用R中的tcltk包创建一个GUI,我正在尝试在R中编写一个函数,在保存时自动将.xlsx扩展名添加到文件名的末尾。但是,当它调用“另存为”窗口时,它不会添加扩展名。感谢任何帮助,谢谢。

library(openxlsx)
library(tcltk)
saveFile1 <- function(){
  write.xlsx(c, tclvalue(tkgetSaveFile(
    filetypes = "{ {Excel} {*.xlsx} }")))
}

1 个答案:

答案 0 :(得分:1)

我认为这应该可以解决问题。

saveFile1 <- function(c){
  require(tcltk)
  require(openxlsx)

  # Prompt for file
  filepath <- tclvalue(tkgetSaveFile(filetypes = "{ {Excel} {*.xlsx} }", defaultextension = ".xlsx"))

  # Check if file was specified
  if(filepath != ""){
    # Ensure that the last 5 characters are .xlsx
    filepath <- ifelse(substr(filepath, nchar(filepath) - 4, nchar(filepath)) == ".xlsx", filepath, paste0(filepath,".xlsx"))

    # Write the file
    write.xlsx(c, filepath)
  }
}

# Test the function
saveFile1(mtcars)
相关问题