0

Suppose I have 3 files named

JohnDoe, PeterGynn, JolieHope

in a folder and now I would like to change the filename from matching values of a data frame df1.

df1 <- structure(list(employee = c("John Doe", "Peter Gynn", "Jolie Hope"), salary = c(21000, 23400, 26800)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

so the final file name would be

21000, 23400, 26800

Basically, I want to change the file name from the matching employee column to the salary column. I can do it in bash

find . -type f -name "*.txt" -printf "/%P\n" | while read FILE ; do DIR=$(dirname "$FILE" );\

but donot know in r

Any help? Thanks in advance

SUMIT
  • 563
  • 4
  • 12
  • 1
    Have you had a look at this question? https://stackoverflow.com/questions/10758965/how-do-i-rename-files-using-r – Peter Aug 23 '21 at 13:10
  • @peter It for adding suffix, prifix or removing some specific character. I want to change the file name from matching row to another column row. – SUMIT Aug 23 '21 at 13:16

1 Answers1

1

this is just before the operation

setwd('~/Desktop/Stack/')

list.files()

output :

'JohnDoe''JolieHope''PeterGynn'

here is how I did;

library(dplyr)

df1 <- structure(list(employee = c("John Doe", "Peter Gynn", "Jolie Hope"), salary = c(21000, 23400, 26800)), row.names = c(NA, -3L), class = c("data.table", "data.frame"))

df1 %>%
mutate(filename=gsub(' ','',employee)) -> df2

for(i in 1:nrow(df2)){
    
    old_name <- df2[i]$filename
    new_name <- as.character(df2[i]$salary)
    
    file.rename(from=old_name,to = new_name)

}

and this is after

list.files()

'21000''23400''26800'
Samet Sökel
  • 2,515
  • 6
  • 21