0

I have multiple xlsx data files with different number of rows. How can I merge them into a data frame? My code

library(readxl)

fnames <- list.files()

xlxs <- lapply(fnames, read_xlsx)

a<-data.frame(xlxs)

But the last line does not work since number of rows are not same for all files.

alistaire
  • 42,459
  • 4
  • 77
  • 117
ash1
  • 393
  • 1
  • 2
  • 10

2 Answers2

0

We can use

library(dplyr)
a <- bind_rows(xlxs)

Also, it is better to specify the pattern

fnames <- list.files(pattern = "\\.xlsx", full.names = TRUE)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    I often also like to have the input filenames referenced in the final data frame. You can use `xlsx <- setNames(xlsx, fnames)`, then add .id = "input_filename" to the bind_rows call to get it easily. – rosscova May 28 '21 at 00:46
0

The purrr option from @alistaire are likely better options, but in case anyone needs/wants to do this in base, you can do:

a <- do.call(rbind, xlsx)
akrun
  • 874,273
  • 37
  • 540
  • 662
rosscova
  • 5,430
  • 1
  • 22
  • 35