5

I would like to direct output to a file, using a write.csv statement. I am wanting to write 16 different output files, labeling each one with the extension 1 through 16.

Example as written now:

    trackfilenums=1:16
    for (i in trackfilenums){
       calculations etc
       write.csv(max.hsi, 'Severity_Index.csv', row.names=F)
    }

I would like for the output csv files to be labeled 'Severity_Index_1.csv', 'Severity_Index_2.csv', etc. Not sure how to do this in R language.

Thanks! Kimberly

kimmyjo221
  • 685
  • 4
  • 10
  • 17

3 Answers3

13

You will want to use the paste command:

write.csv(max.hsi, paste0("Severity_Index_", i,".csv"), row.names=F)
juba
  • 47,631
  • 14
  • 113
  • 118
Sarah
  • 731
  • 7
  • 15
  • 1
    The variable is already here as `i`, and you can use `paste0` to shorten the code a bit. Which gives : `paste0('Severity_Index_',i,'.csv')` – juba Sep 19 '13 at 19:11
  • you're right @juba, I completely missed the 'i'.I've updated my answer to reflect it. I didn't know about the paste0 command - Thanks! – Sarah Sep 19 '13 at 19:14
1

Some people like to have file names like Name_01 Name_02 etc instead of Name_1 Name_2 etc. This may, for example, make the alphabetical order more reasonable: with some software, otherwise, 10 would come after 1, 20 after 2, etc.

This kind of numbering can be achieved with sprintf:

sprintf("Severity_Index_%02d.csv", 7)

The interesting part is %02d -- this says that i is an integer value (could actually use %02i as well) that will take at least 2 positions, and leading zero will be used if necessary.

# try also
sprintf("Severity_Index_%03d.csv", 7)
sprintf("Severity_Index_%2d.csv", 7)
lebatsnok
  • 6,329
  • 2
  • 21
  • 22
0

To add to the other answers here, I find it's also a good idea to sanitise the pasted string to make sure it is ok for the file system. For that purpose I have the following function:

fsSafe <- function(string) {
 safeString <- gsub("[^[:alnum:]]", "_", string)
 safeString <- gsub("_+", "_", safeString)
 safeString
}

This simply strips out all non-alphabetic and non-numeric characters and replacing them with an underscore.

Scott Ritchie
  • 10,293
  • 3
  • 28
  • 64