How to rename multiple objects in r? Or how objects can be recognised with "-" in their name in r?

817 Views Asked by At

I have read a large number of CSV files into R and foolishly the data frames have been saved with "-" symbol in their names, for instance "new-zealand_kba". Is there a way to replace "-" with "_" for a large number of objects. Eg "new-zealand_kba" would become "new_zealand_kba".

Alternatively, is there a way to read in large numbers of CSV files where "-" in their file names are replaced with "_".

# reading in all the CSV files in the folder "Oceania"
path <- "C:/Users/Melissa/Desktop/Dissertation/DATA/Oceania/"
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
  perpos <- which(strsplit(file, "")[[1]]==".")
  assign(
    gsub(" ","",substr(file, 1, perpos-1)), 
    read.csv(paste(path,file,sep="")))
}

# merging all the CSV files with the same country
# is it this section of my code which wont run as new-zealand_red etc is not
# recognised properly.
new-zealand1<-full_join(new-zealand_red, new-zealand_kba, by = "Year")
new-zealand2<-full_join(new-zealand1, new-zealand_con, by = "Year")
new-zealand3<-full_join(new-zealand2, new-zealand_rep, by = "Year")

1

There are 1 best solutions below

0
thothal On BEST ANSWER

You are using assign to create your data.frames. Here you can change the name:

assign(
   gsub("-", "_", gsub(" ","",substr(file, 1, perpos-1))), 
   read.csv(paste(path,file,sep="")))

However, assign maybe not the best option and maybe you should consider storing a list of data frames instead of each data frame separately, for instance like this (untested):

list_of_dataframes <- lapply(files, function(file) read.csv(paste(path,file,sep=""))))

Then all your data frames would sit in a list. You could assign names to this list easily:

names(list_of_dataframes) <- gsub("[ -]", "_", gsub("\\.csv$", "", files)))

If you do not want to re-read your data and you want to rename existing data frames you could the following:

 all_obj <- ls()
 for (old_name in all_aobj) {
    new_name <- make.names(old_name) ## get a syntactical correct name
    if (new_name != old_name) {
        assign(new_name, get(old_name))
        rm(old_name)
    }
 }

Note. This code will also rename valid infix operators like %||%, so starting with a better selection for all_obj would be recommended.