【问题标题】:How to extract comments from multiple similar structured excel files in R?如何从 R 中多个相似的结构化 excel 文件中提取评论?
【发布时间】:2019-09-15 21:58:58
【问题描述】:

我有 1000 个结构相同的 .xlsx 文件。所有内容都包含一个标题行(id、填充日期、项目 1 到 11)和一个带值的行。第 11 项下的单元格包含大多数文件中的注释。如何从所有文件中提取 cmets 并将它们组合成 R 中的单个对象?

我设法通过创建文件列表files <- list.files(pattern = "*.xlsx", full.names = T) 将所有文件合并到一个data.frame 中,使用sapply(files, read_excel) 将它们读入R 并将它们与bind_rows() 组合但是,read_excel 不会导入厘米。为此,我使用了 readxl 和 dplr 包。

我还设法使用xlsx_cells("file.xlsx") 和x[x$address=="N8", c("address", "comment")] 从单个文件中提取评论,但我不知道如何处理多个文件。我使用了包dplr和tidyxl这个方法。

非常感谢您的帮助!

【问题讨论】:

    标签: r excel import


    【解决方案1】:

    这是一种使用purrr的方法:

    编辑:更改解决方案以输出每个注释的源文件并处理缺少此类注释的文件,因为 OP 指定注释存在于“大多数”文件中。

    library(tidyxl)
    library(purrr)
    
    # First, here's a list of xlsx files in the directory:
    file_list <-  list.files() %>%
      .[str_detect(., ".xlsx")]
    file_list
    #[1] "test1.xlsx"            "test2.xlsx"            "test3 no comment.xlsx"
    
    
    # Make a new tibble with two columns: 
    #   file_name   is the source file we're looking at
    #   comments    extracts the comments in N8, if any
    tibble(file_name = file_list,
           comments = map(file_list,
                          ~ xlsx_cells(.) %>%
                            subset(address == "N8", comment))) %>%
      unnest(comments, keep_empty = TRUE)
    
    
    ## A tibble: 3 x 2
    #  file_name             comment          
    #  <chr>                 <chr>            
    #1 test1.xlsx            Comment in file 1
    #2 test2.xlsx            Comment in file 2
    #3 test3 no comment.xlsx NA     
    

    【讨论】:

    • 感谢乔恩!它有效,str_detect() 和 unnest() 解决了其他一些问题
    • 一点跟进:除了 cmets,我如何获取对象中每个文件的项目 1-10 的值?
    猜你喜欢
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2019-06-21
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 1970-01-01
    相关资源
    最近更新 更多