UCLA Academic Technology Services HomeServicesClassesContactJobs

R Code Fragments
How can I write a fixed format file in R?

You may at times wish to write a data file that conforms to a certain format.  For example, you may have run analysis on a given dataset and want to use the same code to read in and analyze a simulated dataset that you created in R. 

The code below presents an example.  A matrix has been generated containing seven columns of data. Using the sprintf command, we can provide a vector of format strings followed by the values to be formatted. 


n<- 7
m<-5
total<-m*n
mymat<-format(matrix(rnorm(total), nrow=m, ncol=n), nsmall =1, digits=2)
mymat
     [,1]      [,2]      [,3]      [,4]      [,5]      [,6]      [,7]     
[1,] "-0.3818" " 0.5939" "-0.3264" "-0.3730" "-1.0548" " 0.7681" "-0.3881"
[2,] " 1.0615" "-0.4285" "-1.5244" " 0.4343" " 0.0050" " 1.8232" "-0.6379"
[3,] "-0.0724" " 0.4410" " 0.2003" "-1.6565" " 0.5057" " 1.1976" " 0.4964"
[4,] "-0.1853" " 0.0024" "-0.0155" " 0.1757" "-1.6813" " 0.0164" "-1.2455"
[5,] " 0.8870" "-1.5517" "-1.2553" "-0.6721" " 0.3025" "-0.3071" " 0.2846"

afixed<- sprintf("%5.2f%5.2f%5.2f%5.1f%5.1f%2.0f%3.0f",
                  mymat[,1], mymat[,2],mymat[,3],mymat[,4],mymat[,5],
                  mymat[,6],mymat[,7])
                  
afixed <- as.matrix(afixed) 
afixed
     [,1]                            
[1,] "-0.38 0.59-0.33 -0.4 -1.1 1 -0"
[2,] " 1.06-0.43-1.52  0.4  0.0 2 -1"
[3,] "-0.07 0.44 0.20 -1.7  0.5 1  0"
[4,] "-0.19 0.00-0.02  0.2 -1.7 0 -1"
[5,] " 0.89-1.55-1.26 -0.7  0.3-0  0"

We can see that the formats have been applied to the original data.


How to cite this page

Report an error on this page

UCLA Researchers are invited to our Statistical Consulting Services
We recommend others to our list of Other Resources for Statistical Computing Help
These pages are Copyrighted (c) by UCLA Academic Technology Services


The content of this web site should not be construed as an endorsement of any particular web site, book, or software product by the University of California.