【问题标题】:Read second sheet of xlsx file from various subdirectories of a main directory R从主目录 R 的各个子目录中读取第二张 xlsx 文件
【发布时间】:2021-06-02 14:00:14
【问题描述】:

我想根据特定模式为每个子目录阅读包含单词“全部”或“全部”的 Excel 工作簿的工作表。 我试过list.files() ,但它不能正常工作。

files_to_read = list.files(
  path = common_path,        # directory to search within
  pattern = "X - GEN", # regex pattern, some explanation below
  recursive = TRUE,          # search subdirectories
  full.names = TRUE          # return the full path
)
data_lst = lapply(files_to_read, read.xlsx)

【问题讨论】:

    标签: r readxl openxlsx


    【解决方案1】:

    我假设您的子目录具有可识别的相似名称?

    假设,假设:

    1. 您的子目录以“this”开头,并且
    2. 保存在子目录中的文件以文件名“my_file”开头
    3. 您尝试读取的选项卡包含“全部”一词。

    如果您正在阅读的选项卡位于同一位置(例如,每个文件的第二个选项卡),那么您可以将 sheet 中的 read.xlsx 指定为 sheet = 2 会更容易,但如果这不是那么你可以做的一种方法是创建你自己的函数来实现这一点。

    然后

    library(openxlsx)
    
    # getting the name of subdirectories starting with the word 'this'
    my_dir <- list.files(pattern = "^this", full.names = TRUE)
    
    # getting the name of the files starting with 'my_file', e.g. my_file.xlsx, my_file2.xlsx
    my_files <- list.files(my_dir, pattern = "^my_file", full.names = TRUE)
    
    my_read_xlsx <- function(files_to_read, sheets_to_read) {
      
      # files to import
      wb <- loadWorkbook(files_to_read)
      
      # getting the sheet names that contain 'all' or any other strings that you specify
      # ignore.case is there so that case is not sensitive when reading in excel tabs
      ws <- names(wb)[grepl(sheets_to_read, names(wb), ignore.case = TRUE)]
      
      # reading in the excel tab specified as above
      xl_data <- read.xlsx(wb, ws)
      
      return(xl_data)
      
    }
    
    # Using the function created above and import tabs containing 'all'
    my_list <- lapply(my_files, FUN = function(x) my_read_xlsx(x, sheet = "ALL"))
    
    # Converting the list into a data.frame
    my_data <- do.call("rbind", my_list)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 2021-03-03
      • 1970-01-01
      相关资源
      最近更新 更多