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

3 Answers 3

13

You will want to use the paste command:

write.csv(max.hsi, paste0("Severity_Index_", i,".csv"), row.names=F)
Sign up to request clarification or add additional context in comments.

2 Comments

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')
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!
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)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.