[R] Print column headers of summary

Marc Schwartz marc_schwartz at me.com
Thu Jun 18 17:56:22 CEST 2009


On Jun 18, 2009, at 10:05 AM, nmset wrote:

>
> Hello,
>
> This is a newbee question. I would simply like to write in a text  
> file the
> headers of the summary function along with the computed data.
>
> write(summary(x), file="out.txt")
>
> gives only the data.
>
> I have not found a solution on the forum.
>
> Thank you for any help.

summary() returns a named vector and write() will strip the names in  
the output. You could use write.table() on an appropriately  
transformed summary() object such as:

set.seed(1)
x <- rnorm(100)

 > summary(x)
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-2.2150 -0.4942  0.1139  0.1089  0.6915  2.4020

# Change the file name here to your target file
# "" goes to the console
# set 'quote = FALSE' to remove the double quotes

 > write.table(t(summary(x)), file = "", row.names = FALSE)
"Min." "1st Qu." "Median" "Mean" "3rd Qu." "Max."
-2.215 -0.4942 0.1139 0.1089 0.6915 2.402


The easiest thing to do might be to use capture.output() and then use  
write() which will simply output the resultant character vectors to  
the file. An alternative approach would be to use sink(), which will  
then send all subsequent console output to a named file until a  
subsequent sink() is called.  See ?capture.output and ?sink.


 > capture.output(summary(x))
[1] "   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. "
[2] "-2.2150 -0.4942  0.1139  0.1089  0.6915  2.4020 "


 > write(capture.output(summary(x)), file = "")
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-2.2150 -0.4942  0.1139  0.1089  0.6915  2.4020


Note also that write() is a wrapper for cat(), thus you can get the  
same by:

 > cat(capture.output(summary(x)), file = "", sep = "\n")
    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-2.2150 -0.4942  0.1139  0.1089  0.6915  2.4020


HTH,

Marc Schwartz




More information about the R-help mailing list