2
votes

I have an occuring problem. I want to write a text file, but I can't get the column names to appear nicely centered above columns.

An example:

dfr <- data.frame(Name=c("Adam Jones", "Brian Smith", "Peter Stevensson"),
Salary=c(12345, 6789, 234567), Tax=c(2345, 1233, 5263))
> dfr
          Name Salary  Tax
1       Adam Jones  12345 2345
2      Brian Smith   6789 1233
3 Peter Stevensson 234567 5263

I have tried:

write.table(dfr, file = "S:/s2609/sisse/minedata/dfr.txt", + quote = FALSE, append = FALSE, col.names = TRUE, row.names = FALSE)

and:

fdfr <- apply(dfr, 2, format, width = 14, justify = "left")
> write.table(fdfr, file = "S:/s2609/sisse/minedata/dfr.txt",
+ quote = FALSE, append = FALSE, col.names = TRUE, row.names = FALSE)

and:

write.fwf(dfr, file = "S:/s2609/sisse/minedata/dfr.txt", width = c(16, 16, 16), justify = "left", append = FALSE, colnames = TRUE, rownames = FALSE)

and:

dfr.m <- as.matrix(dfr)

 > capture.output( print(dfr.m, print.gap=3, quote = FALSE), file = "S:/s2609/sisse/minedata/dfr.txt")

This centres the column names nicely, but leaves the "row names":

 [1,]
 [2,]
 [3,]
 [4,]

Is there any way to have the column names shown nicely in a text file or to remove these "row names" using capture.output()?

Any help is appreciated!

1
What are you going to use the output for? I would suggest using a tool that will output an HTML table or a LaTeX table rather than trying to wrangle text output...Justin
Good idea! I will look into that.Sisse

1 Answers

3
votes

1) Try this:

library(Hmisc)
print.char.matrix(dfr, cell.align = "cen", col.txt.align = "cen", 
         col.names = TRUE, row.names = FALSE, 
         hsep = " ", vsep = "", csep = "")

which gives:

       Name       Salary  Tax 
    Adam Jones     12345 2345 
    Brian Smith     6789 1233 
 Peter Stevensson 234567 5263 

2) or

print.char.matrix(dfr, cell.align = "cen", col.txt.align = "cen", 
                              col.names = TRUE, row.names = FALSE)

which gives:

+----------------+------+----+
|      Name      |Salary| Tax|
+----------------+------+----+
|   Adam Jones   | 12345|2345|
+----------------+------+----+
|   Brian Smith  |  6789|1233|
+----------------+------+----+
|Peter Stevensson|234567|5263|
+----------------+------+----+