如何重命名 r 中的多个对象?或者如何在 r 中用名称中的“-”识别对象?

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

我已经将大量 CSV 文件读入 R 并且愚蠢地在它们的名称中使用“-”符号保存数据帧,例如 "new-zealand_kba"。有没有办法将大量对象的“-”替换为“_”。例如 "new-zealand_kba" 会变成 "new_zealand_kba".

或者,有没有办法读取大量 CSV 文件,其中文件名中的“-”被替换为“_”。

# 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")

您正在使用 assign 创建您的 data.frames。在这里您可以更改名称:

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

但是,分配可能不是最佳选择,也许您应该考虑存储数据帧列表而不是单独存储每个数据帧,例如像这样(未经测试):

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

那么您所有的数据框都将位于 list 中。您可以轻松地为这个列表分配名称:

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

如果您不想重新读取数据并且想重命名现有数据框,您可以执行以下操作:

 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)
    }
 }

注意。 此代码还将重命名有效的中缀运算符,如 %||%,因此建议从 all_obj 的更好选择开始。