r - 如何将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)
解决方案
在函数中,您没有传递变量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)
推荐阅读
- c# - 我的存储过程在调用时不起作用
- firebase - 本地写入带有附加侦听器的 Firebase RTDB 或 Firestore 是否需要读取操作?
- c++ - 显示固定大小小部件的网格,使其水平适合 QScrollArea
- android - 工人经理的自定义约束
- php - 使用钩子刷新 WordPress 永久链接
- security - FIWARE:物联网代理和上下文代理之间的身份验证
- php - 使用 laravel 5.7.* 数据透视表返回 null
- gremlin - step.map.PropertyMapStep 不能转换为 step.ByModulating
- php - laravel 中的关系数据库删除
- c# - 通过 TCP 接收数据:MemoryStream 包含比预期更多的数据