Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating the names of elements of a fs path character vector in R

I have a fs path character vector with a list of file names like these:

path/to/folder/output_1_CR.csv
path/to/folder/output_2_CR.csv
...
path/to/folder/output_22_CR.csv
...
path/to/folder/output_67_CR.csv 

Here’s the code I used to read in these output files into a fs path character vector:

CR_A_paths <- fs::dir_ls(path = "/path/to/folder", regexp = "[CR].csv$")

I want to update the names of the files with single digits in their file name (e.g. output_1_CR.csv, output_5_CR.csv) such that there’s a 0 before the single digit (i.e. output_1_CR.csv becomes output_01_CR.csv)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any idea on efficient ways to do so?

Thanks!

>Solution :

You could use str_replace:

 to <- stringr::str_replace(CR_A_paths, "\\d+", ~sprintf("%02d", as.numeric(.x)))
 to

[1] "path/to/folder/output_01_CR.csv"  "path/to/folder/output_02_CR.csv" 
[3] "path/to/folder/output_22_CR.csv"  "path/to/folder/output_67_CR.csv "

Now to update the names use:

 file.rename(CR_A_paths,to)

CR_A_paths <- c("path/to/folder/output_1_CR.csv", "path/to/folder/output_2_CR.csv", 
"path/to/folder/output_22_CR.csv", "path/to/folder/output_67_CR.csv "
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading