【问题标题】:How to read in excel sheets into one data frame in R and skip certain lines如何将excel表格读入R中的一个数据框并跳过某些行
【发布时间】:2020-11-04 02:51:54
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

    标签: r readxl


    【解决方案1】:

    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)
    

    【讨论】:

    • 成功了。所以我差了一个 x。所以没有占位符x,它就不能迭代?一般情况下这是正确的吗?
    • 如果你使用匿名函数,你必须使用x。我还展示了一种无需x 或匿名函数的方法。
    【解决方案2】:

    试试 datapasta 包。它会粘贴您选择的内容。

    Click the example here

    【讨论】:

    • 哇,我不知道我们可以做到这一点,这太酷了!谢谢
    猜你喜欢
    • 1970-01-01
    • 2022-01-04
    • 2019-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多