首页 > 解决方案 > 如何将excel表格读入R中的一个数据框并跳过某些行

问题描述

我正在尝试使用 R 读取具有多张工作表的 excel 文件,并将它们全部合并到一个数据框中,将工作表名称标记到数据框的一列。

然后这一次我遇到了一个问题,即 Excel 表包含 1 行多余的标题,所以我想跳过第 1 行。

在lapply中使用read_excel,我自然会想到只加skip=1比如

mylist <-lapply(excel_sheets(path), read_excel(skip=1)

然后 R 抱怨路径,如果我继续添加路径,它抱怨 read_excel 不是函数。所以我认为可以使用 function(x){} 编写

这完全搞砸了。生成的列表有一个细微的错误,我只有在绘制数据时才发现:它多次复制并粘贴同一张表 1,并在重复数据上添加了正确的表名。

当然我可以手动删除第一行,但我想知道我在哪里犯了错误以及如何修复它。

library(readxl)

#read in excel sheets
#but now I need to skip one line
path <- "/Users/xxx/file.xlsx"
sheetnames <- excel_sheets(path)
mylist <- lapply(excel_sheets(path), function(x){read_excel(path= path,col_names = TRUE,skip = 1)})

# name the dataframes
names(mylist) <- sheetnames

#use Map to bind all the elements of the list into a dataframe
my_list <- Map(cbind, mylist, Cluster = names(mylist))
df <- do.call("rbind", my_list)

标签: rreadxl

解决方案


在函数中,您没有传递变量read_excel中存在的要读取的工作表。sheetnames尝试以下操作:

library(readxl)
path <- "/Users/xxx/file.xlsx"
sheetnames <- excel_sheets(path)
mylist <- lapply(sheetnames, function(x) 
                 read_excel(path,x, col_names = TRUE,skip = 1))
#col_names is TRUE by default so you can use this without anonymous function like
#mylist <- lapply(sheetnames, read_excel, path = path, skip = 1)

# name the dataframes
names(mylist) <- sheetnames

#use Map to bind all the elements of the list into a dataframe
my_list <- Map(cbind, mylist, Cluster = names(mylist))
df <- do.call("rbind", my_list)

推荐阅读