Home > Software engineering >  Renaming files from RStudio with A DF as Reference
Renaming files from RStudio with A DF as Reference

Time:09-07

I'm trying to rename files in a WD folder from RStudio. The files are named with IDs and I want to replace the IDs with names. I have a reference file which is a dataframe(urban_o) with supplierID, companyname, and vendornumber. I tried this for loop but it doesn't seem to work. Error - the condition has length > 1 and only the first element will be used. Any ideas where I'm getting it wrong?

original_names <- list.files()

urba_o <- import("C:\Users\MaangiJ\Downloads\urba_o.xlsx")

# for loop
for (x in original_names){

  if(x == urba_o$supplierid[]){

    file.rename(x,urba_o$CompanyName[])
  }

}

CodePudding user response:

file.rename is vectorized, so no for loop is needed. Something like this should work:

## figure out which files are here and need renaming
rows_to_rename = urba_o$supplierid %in% original_names
## rename them
with(urba_o[rows_to_rename, ], file.rename(supplierid, CompanyName))

If you did want a for loop, this would work (though it will be less efficient, as well as longer to write):

for (i in 1:nrow(urba_o)) {
  if(urba_o$supplierid[i] %in% original_names) {
    file.rename(urba_o$supplierid[i], urba_o$CompanyName[i])
  }
}

Do note that you'll need to follow the file name rules for your operating system. For example, on Windows file names can't have the following reserved characters: <>/\*'":?|

  • Related