Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R programming, naming output file using variable

Tags:

output

r

csv

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

like image 876
kimmyjo221 Avatar asked Sep 19 '13 19:09

kimmyjo221


2 Answers

You will want to use the paste command:

write.csv(max.hsi, paste0("Severity_Index_", i,".csv"), row.names=F)
like image 187
Sarah Avatar answered Nov 13 '22 07:11

Sarah


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)
like image 1
lebatsnok Avatar answered Nov 13 '22 09:11

lebatsnok