0

I have a few files which have a numbering system likes this:

chr001_genetic_file.txt 
chr002_genetic_file.txt 
...
chr022_genetic_file.txt 

As well as another set like this:

genetic_files.001.european.txt
...
genetic_files.022.european.txt

I am trying to run a for loop: for(i in 001 to 022) but R keeps throwing a naming error saying the file genetic_files.1.european.txt doesn't exist.

I could rename all my files which seems like a headache in order to get "i in 1 to 22" to work. Is there a way around this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
tacrolimus
  • 500
  • 2
  • 12
  • 2
    Have you tried using something like `sprintf("%03d", i)`? – duckmayr Aug 05 '20 at 11:30
  • Thanks Ronak, I'm not trying to add 0s, I'm trying to incorporate them into a loop which seems to want to use 1-22. I don't think this is the same – tacrolimus Aug 05 '20 at 11:41
  • @duckmayr is that in place of the beginning of the for loop or is that a transformation step prior to using the files? – tacrolimus Aug 05 '20 at 11:42
  • 2
    If you show your code (loop) we might be able to help better/faster. – Ronak Shah Aug 05 '20 at 11:43
  • 4
    @duckmayr's approach is correct. Use numeric `1:22` to define your loop, and (eg) `paste0("chr", sprintf("%03d", i), "_genetic_file.txt")` to obtain your file names. By the way, one of the `apply` family of functions is both more compact and efficient than a `for` loop, though the differences will be negligible in a simple case like this. – Limey Aug 05 '20 at 11:45
  • 1
    tacrolimus, The latter; @Limey has got the idea I was putting out there – duckmayr Aug 05 '20 at 11:47
  • Try `for(i in sprintf("%03d", 1:22)) { foo(paste0("chr", i, "_genetic_file.txt")) }` – zx8754 Aug 05 '20 at 12:25
  • Also, consider using `list.files()`, instead of patching filenames with paste which might not even exist. – zx8754 Aug 05 '20 at 12:27

0 Answers0