Home > Software design >  How to import data to a named list?
How to import data to a named list?

Time:11-14

I'm able to import data to a list. For example:

write.csv(mtcars, "mtcars.csv")
write.csv(iris, "iris.csv")
files <- list.files(pattern="*.csv")
imported_files <- list()
for(i in seq_along(files)){
  imported_files[[i]] <- readr::read_csv(file = files[[i]])
}
names(imported_files)

NULL

But the imported_files list has no names. I'd like to create a list with the names in them. Something like this:

names(imported_files)
"iris"
"mtcars"

I'm also wondering if it is possible to do this using lapply and purrr::map().

CodePudding user response:

A solution using lapply could be

imported_files <- lapply(files, \(x) readr::read_csv(x))
names(imported_files) <- gsub(".csv", "", files)

names(imported_files)
#> [1] "mtcars" "iris" 

CodePudding user response:

If you don't mind .csv in the name, you could also just use sapply:

files <- list.files(pattern="*.csv")
imported_files <- sapply(files, function(x) readr::read_csv(file = x))
names(imported_files)

[1] "iris.csv"   "mtcars.csv"

If you do mind, probably better to use lapply with names as in the other example, or the below alternative:

files <- sub('.csv', '', list.files(pattern="*.csv"))
imported_files <- sapply(files, function(x) readr::read_csv(file = paste0(x, '.csv')))
names(imported_files)

[1] "iris"   "mtcars"
  • Related