Reputation: 1023
I've seen a couple of other posts on this, and they've suggested loading dataframes into lists, however they've never explained what's an acceptable way to then name the dynamically generated dataframes.
I've come up with the code below and I want to know if it is a good way of doing this or if I will run into problems in the future?
Thanks,
#create the data frames from all csv files into a list
dfs <- lapply(list.files(pattern="*.csv"),read.csv)
#Give them the correct names
names(dfs) <- regmatches(list.files(pattern="*.csv"),regexpr("^[[:alpha:]]+", list.files(pattern="*.csv")))
Also, can I name them and create them at the same time? I don't want to run the risk that the list.files comes back in a different order on the second call and I put the wrong names on the dataframes.
Upvotes: 0
Views: 217
Reputation: 206167
The Map
function will do a better job of automatically naming the elements.
dfs <- Map(read.csv, list.files(pattern="*.csv"))
Then you could further edit the names()
of the list after it's generated. Or you can just save the file name vector rather than calling list.files()
multiple times and use setNames
right away
#create the data frames from all csv files into a list
csvfiles <- list.files(pattern="*.csv")
dfs <- setNames(lapply(csvfiles, read.csv),
regmatches(csvfiles,regexpr("^[[:alpha:]]+", csvfiles))
)
Upvotes: 5