kimmyjo221
kimmyjo221

Reputation: 715

R programming, naming output file using variable

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

Upvotes: 5

Views: 19808

Answers (3)

Scott Ritchie
Scott Ritchie

Reputation: 10543

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.

Upvotes: 0

lebatsnok
lebatsnok

Reputation: 6479

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)

Upvotes: 1

Sarah
Sarah

Reputation: 741

You will want to use the paste command:

write.csv(max.hsi, paste0("Severity_Index_", i,".csv"), row.names=F)

Upvotes: 13

Related Questions