【问题标题】:Aggregate data from multiple excel files with the same structure聚合来自具有相同结构的多个 excel 文件的数据
【发布时间】:2021-04-19 06:33:44
【问题描述】:

我准备了一项调查,收件人必须填写一个 Excel 文件。我现在有一百个结构相同但条目不同的 excel 文件。例如,对于接收者_b,我们有:

每个 Excel 文件都以收件人的名字命名。例如:recipient_a_survey.xlsx; recipient_b_survey.xlsx 等

我想获得这样的数据框:

Name         birth_place birth_date domicile
recipient_a  London      21/04/1965 London
recipient_b  Manchester  19/02/1985 London
recipient_c  Glasgow     14/08/1991 Edinburgh
...

有什么奇特的方法吗?这种方法也适用于 excel 中的列表。

【问题讨论】:

    标签: r excel dataset aggregate


    【解决方案1】:

    您可以使用 list.files 创建一个要读取的 excel 文件向量,转置它们并将它们绑定到一个对象中 (result)。

    library(tidyverse)
    
    file_list <- list.files('folder/of/excelfiles', pattern = '\\.xlsx$', full.names = TRUE)
    
    map_df(file_list, ~{
      df <- readxl::read_excel(.x)
      df %>%
        mutate(col = c('domicile', 'birth_date', 'birth_place')) %>%
        select(-a) %>%
        pivot_wider(names_from = col, values_from = b) %>%
        mutate(Name = tools::file_path_sans_ext(basename(.x)), .before = 1)
    }) -> result
    
    result
    

    【讨论】:

      猜你喜欢
      • 2011-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多