Hulleo
Hulleo

Reputation: 13

Importing multiple R files into list and storing each element as file name to retrieve

I'm wanting to import multiple rds files within a certain folder into a list, and store these dataframes in the list as their filename. For example, let's say that we have two files within a folder: "apples.rds" and "pears.rds".

To import them I've got:

df_list <- list.files(pattern = "*.rds") %>%
  map(readRDS)

But these are stored as df_list[1] and df_list[2], when I want them to be df_list[apples] and df_list[pears] so that I can retrieve these dataframes later by their name. How can I do this?

Upvotes: 1

Views: 335

Answers (2)

Edward
Edward

Reputation: 18543

names(df_list) <- list.files(pattern = "*.Rds")

Upvotes: 0

lroha
lroha

Reputation: 34301

This should work:

flist <- list.files(pattern = "\\.rds$")

df_list <- setNames(lapply(flist, readRDS), tools::file_path_sans_ext(flist))

Upvotes: 2

Related Questions