Import Files to R

1

Is there a way to import files without having to make a unique file name?

That is:

SURTIDORES <- read_excel("/home/po11/Desktop/nombre1.xlsx")

After

SURTIDORES <- read_excel("/home/po11/Desktop/nombre2.xlsx") 

That there is no need to match the name of the file with the code, the headers of all the files will be equal.

    
asked by Pedro R. Orozco 19.12.2018 в 21:07
source

1 answer

1

The simplest way, using base functionality (except readxl ) could be:

library(readxl)

file.list <- list.files(pattern='*.xlsx')
df.list <- lapply(file.list, read_excel)
df.final <- do.call("rbind", df.list)

Detail:

  • With file.list <- list.files(pattern='*.xlsx') we generate a list starting from the *.xlsx , with which we will have in it the names of the files that we are going to read
  • With df.list <- lapply(file.list, read_excel) implicitly scroll through the list and read each file, the result will be a new list df.list where each element will be data.frame generated from each file
  • Finally, with do.call("rbind", df.list) we combine all dataframe into a single one, obviously the structure of them must be identical to be able to combine them.

Now, if you dare to use tidyverse (I recommend it), you can take advantage of the pipe %>% and the routines map* of the package purrr to do something much more simple and concrete:

list.files(pattern='*.xlsx') %>%    # Con la lista de archivos
    map_df(read_excel) -> df.final  # leemos los excel y retornamos un único df
    
answered by 19.12.2018 в 23:15