首页 > 解决方案 > R read.xlsx 注释字符选项

问题描述

我正在使用包中的read.xlsx功能openxlsx。简单地说,我想知道是否有任何解决方法来识别工作表中的评论标题。

例如,如果工作表看起来很喜欢

# information about data
ID    Value
A    10
B    3
C    19

我希望能够以与.txt 文件read.xlsx类似的方式使用,并使用了read.xlsx 不存在的选项。read.delimcomment.char = "#"

## ideal code    
df <- read.xlsx("data.xlsx", sheet = 1, comment.char = "#")

我显然可以使用该startRow选项,但这需要我手动查看每张纸并确定有多少注释行。

我对解决方法的想法是如何查看工作表并返回开头包含 # 的行数并将此变量传递给startRow选项。关于如何/如果这是可能的任何想法?或者我错过的任何其他功能/选项?

标签: rimport

解决方案


您可以为处理这种情况的 read.xlsx 编写自己的包装函数,就像这样......

这假设 Book1.xlsx 在第一张表中包含您的示例数据。

library(openxlsx)

wb_file <- "Book1.xlsx"

wb <- loadWorkbook(wb_file)

#custom function to skip header comment rows
read.xlsx.skip.comment <- function(wb, comment.char = "#", ...){

  #read data from sheet 1
  shx <- read.xlsx(wb, ...)

  #count comment rows
  skip.rows <- grep(paste0("^", comment.char), c(names(shx)[1], shx[ , 1]))

  #skip comment header rows if they exist
  if(length(skip.rows) > 0) shx <- read.xlsx(wb, startRow = max(skip.rows) + 1, ...)

  return(shx)
}

#call the function, use default comment.char
foo <- read.xlsx.skip.comment(wb = wb, sheet = 1)

请注意,...允许指定其他 read.xlsx 参数(例如,工作表)。


推荐阅读