Search code examples
rheadermatrixmultilinefixed-width

Add Matrix to multiline Header in R


I've got a headerfile with exactly 4 rows in a fixed width format (saved with the write.matrix function from the MASS package).

Now I want to create a new Matrix with the headerfile I created above. Is it possible in R to add a fixed multiline header (e.g. as "text") to a matrix?

An example: I've got a header like

AB
CDEF 123456
GHIJK 789     101112
LMNOP

And then I want to create a matrix with date in first column and then the data (from another file) in the second column like

892201 0.1
892202 0.8

and so on. Note: It has to be the described format, because the program just read the fixed width format explained above.


Solution

  • You can write the second set of data into the existing file using the write.table() function with the append = TRUE argument.

    If I have file foo.txt with the header you show, then I can add some dates and other data to that file by first creating the data object I want to append:

    dat <- data.frame(dates = Sys.Date() + 0:4, data = seq(0.1, 0.5, by = 0.1))
    
    > dat
           dates data
    1 2012-06-12  0.1
    2 2012-06-13  0.2
    3 2012-06-14  0.3
    4 2012-06-15  0.4
    5 2012-06-16  0.5
    

    The the following will append dat without any extraneous headers or row names on to the existing header file

    write.table(dat, "foo.txt", append = TRUE, col.names = FALSE, row.names = FALSE)
    

    foo.txt now looks like this:

    $ cat foo.txt
    AB
    CDEF 123456
    GHIJK 789     101112
    LMNOP
    2012-06-12 0.1
    2012-06-13 0.2
    2012-06-14 0.3
    2012-06-15 0.4
    2012-06-16 0.5