Assign names of elements in list to file name in R

I have a list of more than 50 csv data frames. I am listing my files from folder using:

#list files   
estaciones <- list.files(path = "Path",
                                 recursive = T, pattern = ".csv", full.names = T)


[1] "D:/A/Stations/AngosturaCochea_108013/Angostura_Cochea.csv"      
[2] "D:/A/Stations/BocadeTrampa_162003/BocadeTrampa_162003.csv"      
[3] "D:/A/Stations/Caimito_140005/Caimito_140005.csv"      

#read csvs
estaciones2 = lapply(estaciones, read.csv)

I want to set the names to each of my elements in the list to its original CSV file name.

I have tried using this but its not really doing it for me:

estaciones3 <- setNames(estaciones2, substr(list.files("Path", pattern=".csv"))

How can I assign names of files to my list elements?

1 answer

  • answered 2021-07-26 14:07 Ronak Shah

    You can use -

    estaciones2 = lapply(estaciones, read.csv)
    names(estaciones2) <- tools::file_path_sans_ext(basename(estaciones))

    where tools::file_path_sans_ext would return the filename without extension i.e csv.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum