Andy.Jian Andy.Jian - 1 year ago 55
R Question

How to get named list when reading multiple csv files from given folder?

Assume I have several csv files in given folder, When I read them, I could have unnamed list where each list element has default numeric index. How can I read them as named list instead ? Here is my code what I've done:

Regarding the reproducible data, it is allowed to use public dataset

file <- list.files(folder, full.names = TRUE, "\\.csv$") <- lapply(1:length(file), function(ele_) {
res <- as(read.csv(file[ele_]), "data.frame")

I am expecting to have named list instead of default unnamed list, how can I get easily my expected output? Any idea ?

my desired output would be :
after I read cvs files from given folder, each list element must have specific name instead of default numeric index.
How can I get my expected output easily? Does anyone know possible way getting this output? Thank you

Answer Source

We can use setNames with the extracted file names (with basename and file_path_sans_ext)

setNames(lapply(file, read.csv), tools::file_path_sans_ext(basename(file)))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download