Adding folder name as a prefix to file name in R

744 Views Asked by At

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

There are 1 best solutions below

2
Rui Barradas On

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