Read multiple xlsx files with multiple sheets into one R data frame

前端 未结 4 700
轮回少年
轮回少年 2020-12-09 00:26

I have been reading up on how to read and combine multiple xlsx files into one R data frame and have come across some very good suggestions like, How to read multiple xlsx f

4条回答
  •  盖世英雄少女心
    2020-12-09 01:01

    I would use a nested loop like this to go through each sheet of each file. It might not be the fastest solution but it is the simplest.

    require(xlsx)    
    file.list <- list.files(recursive=T,pattern='*.xlsx')  #get files list from folder
    
    for (i in 1:length(files.list)){                                           
      wb <- loadWorkbook(files.list[i])           #select a file & load workbook
      sheet <- getSheets(wb)                      #get sheet list
    
      for (j in 1:length(sheet)){ 
        tmp<-read.xlsx(files.list[i], sheetIndex=j, colIndex= c(1:6,8:10,12:17,19),
                       sheetName=NULL, startRow=4, endRow=NULL,
                       as.data.frame=TRUE, header=F)   
        if (i==1&j==1) dataset<-tmp else dataset<-rbind(dataset,tmp)   #happend to previous
    
      }
    }
    

    You can clean NA values after the loading phase.

提交回复
热议问题