Search code examples
rsaveseparator

in R: save text file with different separators for each column?


Is it possible in R to save a data frame (or data.table) into a textfile that contains different separators for various columns? For example: Column1[TAB]Column2[,]Column3 ?

[] indicate the separators, here a TAB and comma.


Solution

  • The function write.table accepts only one separator.

    MASS::write.matrix can do the trick:

    require(MASS)
    m <- matrix(1:12, ncol = 3)
    write.matrix(m, file = "", sep = c("\\tab", ","), blocksize = 1)
    

    returns

    1\tab5,9
     2\tab 6,10
     3\tab 7,11
     4\tab 8,12
    

    but as the documentation of this function does not say that multiple separators are allowed, it may be safer to do it by yourself, just in case the above has some side effects.

    For example,

    seps <- c("\\tab", ",", "\n")
    apply(m, 1, function(x, seps) 
      cat(x, file = "", sep = seps, append = TRUE), seps = seps)
    

    returns

    1\tab5,9
    2\tab6,10
    3\tab7,11
    4\tab8,12
    

    Be aware that append is set to TRUE, so if the output file already exists it will be overwritten.