1

I would like to add the folder name in front of all file names being in this folder.

My folder name is TempAir, all file names within this folder are "201401.tif" "201402.tif" "201403.tif" "201404.tif" "201405.tif"

files.old <- list.files(path = "TempAir")

Output:

[1] "201401.tif" "201402.tif" "201403.tif" "201404.tif" "201405.tif"

I would like to add TempAir as a prefix to all files like;

"TempAir_201401.tif" "TempAir_201402.tif" "TempAir_201403.tif" "TempAir_201404.tif" "TempAir_201405.tif"

And I try to write the code, following the suggestion of @Rui Barradas like this

files.new <- paste("TempAir", files.old, sep = "_")
files.new

Output:

[1] "TempAir_201401.tif" "TempAir_201402.tif" "TempAir_201403.tif" "TempAir_201404.tif" "TempAir_201405.tif"

And then I run the code to rename the files below

file.rename(files.old, files.new)

But, the result showed FALSE output like this

Output:

[1] FALSE FALSE FALSE FALSE FALSE

What should I edit these code? Please advise

Thank you,

Kanokporn

1 Answers1

0

Here is a way to add a path to a vector. The default is the working directory.

add_prefix <- function(x, path = basename(normalizePath(".")), sep = "_"){
  paste(path, x, sep = sep)
}

add_prefix(files.old)

Data

files.old <- scan(what = character(), 
                  text = '"201401.tif" "201402.tif" "201403.tif" "201404.tif" "201405.tif"')
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
  • Thank you for your help, I have run your code already, and it works for adding folder name as a prefix. But I still cannot rename the new file names by using file.rename(). Could you advise me further? – Kanokporn PROMNIKORN Jan 23 '22 at 18:06
  • @KanokpornPROMNIKORN Why can't you rename the file? Is there an error? Please describe what went wrong. – Rui Barradas Jan 23 '22 at 22:05