首页 > 解决方案 > 在R中的表中合并多个保存为xls的html

问题描述

我有一个包含多个扩展名为 .xls 的 html 文件的文件夹。

数据样本

我需要将它们组合在一个表中:

我开始阅读文件夹中的文件:

library(rvest)
library(tibble)

file_list <- list.files(pattern = '*.xls')

html_df <- lapply(file_list,function(x)read_html(x))

我不知道如何从这里开始从每个文件中提取表并组合在一起

标签: rmerge

解决方案


如果所有文件的格式与您上传的示例相同,这应该可以工作:

library(rvest)

file_list <- list.files(pattern = '*.xls')
data <- 
  purrr::map_dfr( # use map_dfr() to combine data frames
    file_list,
    function(x) {
      read_html(x) %>%
        html_node("table") %>% # read the first 'table' node (which is the only one in the sample)
        html_table(fill = T) %>% # fill it because the table is not neat yet
        setNames(.[1, ]) %>% # use the first row to set column names
        .[-c(1, nrow(.)), ] # chop the first row which is the repeated column names and the last row which is the total row
    }
  )

推荐阅读