r - R read.xlsx 注释字符选项
问题描述
我正在使用包中的read.xlsx
功能openxlsx
。简单地说,我想知道是否有任何解决方法来识别工作表中的评论标题。
例如,如果工作表看起来很喜欢
# information about data
ID Value
A 10
B 3
C 19
我希望能够以与.txt 文件read.xlsx
类似的方式使用,并使用了read.xlsx 不存在的选项。read.delim
comment.char = "#"
## ideal code
df <- read.xlsx("data.xlsx", sheet = 1, comment.char = "#")
我显然可以使用该startRow
选项,但这需要我手动查看每张纸并确定有多少注释行。
我对解决方法的想法是如何查看工作表并返回开头包含 # 的行数并将此变量传递给startRow
选项。关于如何/如果这是可能的任何想法?或者我错过的任何其他功能/选项?
解决方案
您可以为处理这种情况的 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 参数(例如,工作表)。
推荐阅读
- javascript - 如何使用Backbone js中的函数从视图中调用另一个视图
- php - 如何从 foreach 循环中对刀片文件中的 linetotal 求和
- build - SCons:清理失败后重建
- php - Foreach 在对象中的值之后
- ruby-on-rails - Rails where(id: [1, 2, 3]) 查询如何获取搜索失败的id?
- c++ - C++ Winsock Google 搜索查询 GET 请求
- database - 如何将增量加载到 SQL 中
- java - STS 工具套件一直挂着
- python - 子串匹配然后用迭代打印
- python - 指定用于 Keras Tensorflow 模型推理的 CPU