Motivation

Sometimes we want to store intermediate results, e.g. model parameters for several conditions, into a file as table. The results for one condition should be all in one row.

For this, we need to everride the deafult write argument ncolumns.

Data

Prepare a vector

file <- "bla.txt"
x <- 1:6
names(x) <- c(letters[1:length(x)])
x
## a b c d e f 
## 1 2 3 4 5 6

Writing

By default, write writes each character vector elements into a separate line. Numerical vector elements are written in groups of five elements per line.

If we want to have all vector elements in one line, we have to set the number of columns argument to the vector length.

Start by writing the header into a new file.

write(names(x), file
      , sep="\t"
      , ncolumns=length(names(x))
      )

Then append the vectors line by line.

for(i in 1:3) {
  y <- 10 * i + x
  write(y, file
        , sep="\t"
        , append=TRUE
        , ncolumns=length(y)
        )
}

Read back

Read the composed table:

read.table(file
           , header=TRUE
           , sep="\t"
           )
##    a  b  c  d  e  f
## 1 11 12 13 14 15 16
## 2 21 22 23 24 25 26
## 3 31 32 33 34 35 36