Skip to Main Content

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

Version info: Code for this page was tested in R Under development (unstable) (2012-07-05 r59734)
On: 2012-08-08
With: knitr 0.6.3

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.

set.seed(1)
(mymat <- round(matrix(rnorm(5 * 7), nrow = 5, ncol = 7), digits = 3))
##        [,1]   [,2]   [,3]   [,4]   [,5]   [,6]   [,7]
## [1,] -0.626 -0.820  1.512 -0.045  0.919 -0.056  1.359
## [2,]  0.184  0.487  0.390 -0.016  0.782 -0.156 -0.103
## [3,] -0.836  0.738 -0.621  0.944  0.075 -1.471  0.388
## [4,]  1.595  0.576 -2.215  0.821 -1.989 -0.478 -0.054
## [5,]  0.330 -0.305  1.125  0.594  0.620  0.418 -1.377
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))
##      [,1]                            
## [1,] "-0.63-0.82 1.51 -0.0  0.9-0  1"
## [2,] " 0.18 0.49 0.39 -0.0  0.8-0 -0"
## [3,] "-0.84 0.74-0.62  0.9  0.1-1  0"
## [4,] " 1.59 0.58-2.21  0.8 -2.0-0 -0"
## [5,] " 0.33-0.30 1.12  0.6  0.6 0 -1"

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