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")
You are using
assignto create yourdata.frames. Here you can change the name: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):
Then all your data frames would sit in a
list. You could assign names to this list easily:If you do not want to re-read your data and you want to rename existing data frames you could the following:
Note. This code will also rename valid infix operators like
%||%, so starting with a better selection forall_objwould be recommended.