使用R从excel中提取数据

我必须从超过100个excel文件中提取特定的数据段。 问题是跨这些文件的总行不是恒定的。 有没有办法阻止R读取基于Excel中的一个stringvariables的数据?

这里给出的图像

您可以只读取每个Excel文件的前两列,然后通过利用每个Excel文件结构中的规则,确定并保留第一个表中的行。

这是一个使用readxl包中的read_excel函数来读取数据的方法。 我们只读取Excel文件的前两列。 read_excel自动修剪空白区域,并从第一个非空行开始读取。

在读取数据后,我们有一个有两列的数据框。 我们现在需要做出以下改变:

  1. 将列名称重置为正确的值。
  2. 删除第一个数据行,因为这些行最初是列名
  3. 删除第一个表之后的行。 由于第二个表格以“时间logging详细信息”开始,所以我们只将数据框行保留至小于第一列中出现的行号的行号。

 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 

要读取多个文件,可以将它们全部读入dataframe列表中,如下所示:

 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), ] }) 

下面是我创build的用于testing代码的示例Excel文件的图片:

在这里输入图像说明