MYa*_*208 5 excel r data.table
我的 Excel 文档my.xlsx有两个名为Sheet1和Sheet2 的工作表。我想使用包中的fread函数读取 Excel 工作簿中的所有工作表data.table R。以下代码仅读取活动工作表。想知道如何在不知道名称的情况下阅读所有工作表。谢谢
df3 <- data.table::fread("in2csv my.xlsx")
> names(df3)
[1] "A" "B"
> df3
A B
1: 1 2
2: 2 4
3: 3 6
4: 4 8
5: 5 10
Run Code Online (Sandbox Code Playgroud)
openxlsx::read.xlsx上次我需要从 XLSX 中读取很多张纸时,我使用了它。
#install.packages("openxlsx")
library(openxlsx)
#?openxlsx::read.xlsx
#using file chooser:
filename <- file.choose()
#or hard coded file name:
#filename <- "filename.xlsx"
#get all the sheet names from the workbook
SheetNames<-getSheetNames(filename)
# loop through each sheet in the workbook
for (i in SheetNames){
#Read the i'th sheet
tmp_sheet<-openxlsx::read.xlsx(filename, i)
#if the input file exists, append the new data;; else use the first sheet to initialize the input file
ifelse(exists("input"),
input<-rbind(input, tmp_sheet),
input<-tmp_sheet)
}
Run Code Online (Sandbox Code Playgroud)
注意:这假设每个工作表具有相同的列结构和数据类型。您可能需要标准化\规范化数据(例如tmp_sheet <- as.data.frame(sapply(tmp_sheet,as.character), stringsAsFactors=FALSE)),或将每个工作表加载到它自己的数据框中并在合并之前进一步进行预处理。