您可以只读取每个 Excel 文件的前两列,然后利用每个 Excel 文件结构中的规律性,识别并仅保留第一个表中的行。
这是一种使用readxl 包中的read_excel 函数读取数据的方法。我们只读取了 Excel 文件的前两列。 read_excel 自动修剪空白并从第一个非空行开始读取。
读入数据后,我们有一个包含两列的数据框。我们现在需要进行以下更改:
- 将列名重置为正确的值。
- 删除第一个数据行,因为它们最初是列名
- 删除第一个表之后的行。由于第二个表以“时间记录详细信息”开头,因此我们将数据框的行保留到比该文本出现在第一列中的行号少 2 的行号。
library(readxl)
# Read first two columns
df = read_excel("Workbook1.xlsx", col_types=c("text","numeric"), range=cell_cols("A:B"))
# Reset column names
names(df) = c("Project", "Hours")
# Remove first row (which contains the column names form the excel file)
df = df[-1, ]
# Remove rows after the end of the first table
df = df[1:(which(df[,1]=="Time Recording Details") - 2), ]
下面是使用下面显示的示例 Excel 文件的输出:
df
Project Hours
1 A 1
2 B 2
3 A 3
4 B 4
5 A 5
6 B 6
7 A 7
要读取多个文件,可以将它们全部读取到数据框列表中,如下所示:
files = list.files(pattern="xlsx")
df.list = lapply(files, function(f) {
# Read first two columns
df = read_excel(f, col_types=c("text","numeric"), range=cell_cols("A:B"))
# Reset column names
names(df) = c("Project", "Hours")
# Remove first row (which contains the column names form the excel file)
df = df[-1, ]
# Remove rows after the end of the first table
df[1:(which(df[,1]=="Time Recording Details") - 2), ]
})
这是我为测试代码而创建的示例 Excel 文件的图片: