Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename files with a specific pattern in R?

There are some .fcs files in a data.000X format (where X = 1, 2, 3...) in a directory.

I want to rename every n file to the following format: exp.fcs (where exp is a text from a vector) if the file to be renamed is an .fcs file.

in other words: I want to rename files to exp.txt, where exp is a text and not a consecutive letter(s) i.e. F, cA, K, etc.

For example, from:

data.0001, data.0002, data.0003, data.0004, data.0005, data.0006...  

to

textF_a.fcs, textF_b.fcs, textF_c.fcs, textVv_a.fcs, textVv_b.fcs, textVv_c.fcs ...  

I tried to do it with file.rename(from, to) but failed as the arguments have different lengths (and I don't know what it means):

a <- list.files(path = ".", pattern = "data.*$")  
b <- paste("data", 1:1180, ".fcs", sep = "")  
file.rename(a, b)
like image 317
abc Avatar asked Oct 22 '11 22:10

abc


People also ask

How do I rename a data file in R?

To rename a file in R, use the file. rename() function. The file. rename() method will rename files, and it can take a vector of both from and to names.

Can I batch change file names?

To batch rename files, just select all the files you want to rename, press F2 (alternatively, right-click and select rename), then enter the name you want on the first file. Press Enter to change the names for all other selected files.


Video Answer


2 Answers

Based on your comments, one issue is that your first file isn't named "data.001" - it's named "data.1". Use this:

b <- sprintf("data%.4d.fcs", seq(a)) 

It prepends up to 3 0s (since it seems you have 1000+ files, this may be better) to indices < 1000, so that all names have the same width. If you really just want to see things like "data.001", then use %.3d in the command.

like image 137
Iterator Avatar answered Sep 29 '22 21:09

Iterator


Your code "works" on my machine ("works" in the sense that, when I created a set of files and followed your procedure, the renaming happened correctly). The error is likely that the number of files that you have (length(a)) is different from the number of new names that you give (length(b)). Post back if it turns out that these objects do have the same length.

like image 36
Charlie Avatar answered Sep 29 '22 21:09

Charlie