Home > Net >  Rename all files in a directory based off of columns in another index data frame
Rename all files in a directory based off of columns in another index data frame

Time:05-20

I have a large number of csv files in a directory that I need to rename based off of corresponding cols in another index/reference data frame. Here is a three element sample of what I'm dealing with:

dir.create("dir1")

write.csv(mtcars[1:2,], "dir1/20821659.csv", row.names=FALSE)
write.csv(mtcars[3:4,], "dir1/20821654.csv", row.names=FALSE)
write.csv(mtcars[5:6,], "dir1/20821657.csv", row.names=FALSE)

Now I have another data frame with the orignial names of these files in one column, and another column that I would like to use to rename them:

location <- c("SFM01_2", "SFM05_2", "02M08_2")

sn <- c("20821659", "20821654", "20821657")

df<- data.frame(location, sn)

For example, the location name that corresponds to the first file name (20821659) is SFM01_2, and I would like to change that file name to SFM01_2 and so on for all the many files in this folder.

CodePudding user response:

You could loop over the rows, each time using paste0() to create a mv command, which is then provided to system()

purrr::walk(1:nrow(df),function(i) {
  cmd = paste0("mv dir1/",df[["sn"]][i], ".csv dir1/", df[["location"]][i], ".csv")
  system(command=cmd)
})

CodePudding user response:

Tested. file.rename returns TRUE on success.

dir1 <- "dir1"
apply(df, 1, \(x) {
  new <- paste0(x[1], ".csv")
  new <- file.path(dir1, new)
  old <- paste0(x[2], ".csv")
  old <- file.path(dir1, old)
  if(file.exists(old)) file.rename(old, new)
})
#[1] TRUE TRUE TRUE

CodePudding user response:

Here is a solution using mapply. You can create a new dataframe with the full paths of the files. Then, rename the file using the specification of the 2 columns row by row .

dir.create("dir1")

write.csv(mtcars[1:2,], "dir1/20821659.csv", row.names=FALSE)
write.csv(mtcars[3:4,], "dir1/20821654.csv", row.names=FALSE)
write.csv(mtcars[5:6,], "dir1/20821657.csv", row.names=FALSE)
list.files('dir1') # "20821654.csv" "20821657.csv" "20821659.csv"

location <- c("SFM01_2", "SFM05_2", "02M08_2")

sn <- c("20821659", "20821654", "20821657")
df<- data.frame(location, sn)

# Create a new dataframe with the full paths of the files
df2 <- sapply(df, function(i){
  paste0('dir1/', i, '.csv')
})
# rename the file using the specification of the 2 columns row by row 
mapply(FUN = file.rename, from = df2[, 2], to = df2[, 1], 
       MoreArgs = NULL, SIMPLIFY = TRUE, USE.NAMES = TRUE)

list.files('dir1') # "02M08_2.csv" "SFM01_2.csv" "SFM05_2.csv"

  • Related