【问题标题】:Check if a data sheet exists in R检查 R 中是否存在数据表
【发布时间】:2016-10-18 09:11:35
【问题描述】:

我有一个闪亮的应用程序,用户可以在其中上传文件。根据此文件是否有 1 个或 2 个数据表,功能应该有所不同。 我用 read.xlsx 导入数据表,其中 data_in 是路径:

data <-read.xlsx(data_in,1,1,colNames=TRUE)

所以这是文件的第一页。当然,第二张表可以以相同的方式导入。但如果它没有第二张纸,我希望它通过粘贴警告或以其他方式继续来处理它。

那么,如何判断数据文件中是否存在第二张表呢?

感谢您的帮助!

谢谢

【问题讨论】:

    标签: r excel shiny


    【解决方案1】:

    XLConnect 包中有一个方法existsSheet 可以检查excel 文件中是否存在工作表。

    您可以尝试以下操作:

    # mtcars xlsx file from demoFiles subfolder of package XLConnect
    demoExcelFile <- system.file("demoFiles/mtcars.xlsx", package = "XLConnect")
    
    # Load workbook
    wb <- loadWorkbook(demoExcelFile)
    
    # Check for existence of a worksheet called 'mtcars'
    existsSheet(wb, "mtcars")
    

    详情请参考this

    【讨论】:

    • 感谢@Nishu Tayal 的回答。这是一种有用的方法,但对于这种情况,我认为不是最好的方法,因为您必须知道工作表的名称。我没有定义用户应该如何调用他的工作表,我也不打算这样做,因为这只会导致更多错误等。
    【解决方案2】:

    您可以使用 readxl 包的 excel_sheets 函数来“列出 excel 电子表格中的所有工作表”。

    library(readxl)
    excel_sheets("path/to/excel/file")
    

    来自文档:

    # To load all sheets in a workbook, use lapply
    path <- system.file("extdata/datasets.xls", package = "readxl")
    lapply(excel_sheets(path), read_excel, path = path)
    

    【讨论】:

      【解决方案3】:

      上面的答案很好地指出了您特定问题的解决方案。我只想为此类问题添加一个通用解决方案:您可以查看tryCatch()。 这允许您定义在代码中出现错误或警告时应该发生的情况。

      result <- tryCatch({
              # The code you want run
          }, warning = function(war) {
              # Is executed if warning encountered
          }, error = function(err) {
              # Is executed if error encountered
          })
      

      在您的示例中,您可以尝试阅读第二张表并定义如果这引发错误应该发生什么。

      【讨论】:

      • 我其实也喜欢这个是的。我不知道从错误中继续的想法,所以我尽量避免它。相反,我认为这更能从根本上解决问题。谢谢。
      【解决方案4】:
      It worked for me with openxlsx
      
      nfile <- "D:\\Temp\\NCLWKBOM.xlsx"
      x <- ""
      y<- ""
      
      # check for file existance
      if (file.exists(nfile)) {
        wb <- loadWorkbook(nfile)
      
      #check sheet existance name(wb) gives name of sheet in wb
      for (x in names(wb)){
          if (x == "NCLBOM") {
            y <- TRUE
          }
        }
        if (y != TRUE) {
          addWorksheet(wb, "NCLBOM")
        }
      
      }else {
        wb <- createWorkbook()
        addWorksheet(wb, "NCLBOM")
      }
      

      【讨论】:

        猜你喜欢
        • 2012-05-29
        • 1970-01-01
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 2019-03-25
        • 1970-01-01
        • 2016-06-13
        相关资源
        最近更新 更多