You can use sprintf as @Andrey Shabalin suggested or as an alternative you can use formatC like so:
id <-1
formatC(id, width=4, flag="0")
[1] "0001"
In your function you have to put this line before you read-in the file:
id <- formatC(id, width=4, flag="0")
Hope this helps.