Search code examples
rwrite.table

How to create a custom write.table function?


I can use write.table function to create an output data from a data.frame:

> write.table(head(cars), sep = "|", row.names=FALSE)
"speed"|"dist"
4|2
4|10
7|4
7|22
8|16
9|10

How can I create my own write.table function which creates an output like this (header with double pipes and data with preceding and succeeding pipes)?:

||"speed"||"dist"||
|4|2|
|4|10|
|7|4|
|7|22|
|8|16|
|9|10|

Solution

  • write.table can get you part of the way, but you will still need to do some fiddling around to get things to work just as you want.

    Here's an example:

    x <- capture.output(
      write.table(head(cars), sep = "|", row.names = FALSE, eol = "|\n"))
    x2 <- paste0("|", x)
    x2[1] <- gsub("|", "||", x2[1], fixed=TRUE)
    cat(x2, sep = "\n")
    # ||"speed"||"dist"||
    # |4|2|
    # |4|10|
    # |7|4|
    # |7|22|
    # |8|16|
    # |9|10|
    

    As a function, I guess in its most basic form it could look something like:

    write.myOut <- function(inDF, outputFile) {
      x <- capture.output(
        write.table(inDF, sep = "|", row.names = FALSE, eol = "|\n"))
      x <- paste0("|", x)
      x[1] <- gsub("|", "||", x[1], fixed=TRUE)
      cat(x, sep = "\n", file=outputFile)
    }