1
votes

I have some files in a base directory that I use to house all my .csv files

base_dir <- file.path(path)
file_list <- list.files(path = base_dir, pattern = "*.csv")

I would like to load all of them at once:

for (i in 1:length(file_list)){
  assign(file_list[i],
  read.csv(paste(base_dir, file_list[i], sep = ""))

)}

However, this produces files with ".csv" in the names in R.

What I would like to do is load all the files but drop the ".csv" from the name once they are loaded.

I have tried the following:

 for (i in 1:length(file_list)){ assign(file_list[i],
 read.csv(substr(paste(base_dir, file_list[i], sep = ""), 1,
 nchar(file_list[i]) -4))
 
 )}

But I received an error: No such file or directory

Is there a way to do this somewhat efficiently?

2

2 Answers

4
votes

Normally one reads them into a list rather than having them as free objects floating around in the workspace. Use dir or Sys.glob to generate the full path names and then use read.csv to read each one in. L's names will be pathnames so reduce them to the basename and remove .csv .

# paths <- dir(path = path, pattern = "\\.csv$", full = TRUE)
paths <- Sys.glob(sprintf("%s/*.csv", path))
L <- Map(read.csv, paths)
names(L) <- sub("\\.csv$", "", basename(names(L)))

If you really want them as free floating objects anyways then add this:

list2env(L, .GlobalEnv)
2
votes

We can use sub to remove the .csv at the end

for (i in 1:length(file_list)){
  assign(sub("\\.csv$", "", basename(file_list[i])),
       read.csv(paste(base_dir, file_list[i], sep = ""))

    )}

Or another option is file_path_sans_ext

for (i in 1:length(file_list)){
  assign(tools::file_path_sans_ext(basename(file_list[i])),
       read.csv(paste(base_dir, file_list[i], sep = ""))

    )}

The error produced in OP's code is because the substr is applied on the 'value' part i.e. the one goes into reading the file instead of the 'x' i.e. the corrected code would be

for(i in 1:length(file_list)){       
     assign(substr(paste(base_dir, file_list[i], sep = ""), 
           1, nchar(file_list[i]) -4),     
         read.csv(file_list[i])

 )}

Also, if the working directory is different, it may be better to specify full.names = TRUE

file_list <- list.files(path = base_dir, pattern = "*\\.csv$", full.names = TRUE)