[R] Adding a header after the file is written
(Ted Harding)
Ted.Harding at manchester.ac.uk
Tue May 4 00:24:58 CEST 2010
On 03-May-10 21:19:34, steven mosher wrote:
> The situation arises where I open a file to write a data.frame
> to it. with write.table.
>
> multiple lines are written to the file and the file is kept in
> Append=TRUE
> mode.
>
> If one sets the col.names to the names of the variables being
> written, you have output that looks like this...
>
> name1 name2 name3.....
>
> x x x
> x x x
> x x x
> name1 name2 name 3
> x x x
> x x x
> x x x
>
> And so forth as each time write is called, the col.names are written.
>
> Setting col.names=NULL obviously removes them.
>
> I thought a simple solution would be to check for the file existence
> first and on the first write, include the col.names. with append=T.
> on subsequent writes, col.names would be set to NULL.
> that didnt work and threw warnings.
>
> Is there anyway to do this. basically open a file for writing, with
> append=TRUE and only write the col.names once at the first write.
> or am I stuck and forced to write the whole file without the col.names
> and then read back in and rewrite with col.names="the cols names I
> want"
The following (which uses a tiny dataframe I had lying around after
responding to an earlier query) looks like what you want to do
(provided you first test existince of the file before switching
to the second form of write.table()):
foo
# $Bar1
# [1] 1
# $Bar2
# [1] 2
# $Bar3
# [1] 3
# $Bar4
# [1] 4
write.table(foo,file="foo.txt",row.names=FALSE,
col.names=c("Bar.1","Bar.2","Bar.3","Bar.4"),
append=FALSE)
write.table(foo,file="foo.txt",row.names=FALSE,
col.names=FALSE,append=TRUE)
write.table(foo,file="foo.txt",row.names=FALSE,
col.names=FALSE,append=TRUE)
write.table(foo,file="foo.txt",row.names=FALSE,
col.names=FALSE,append=TRUE)
write.table(foo,file="foo.txt",row.names=FALSE,
col.names=FALSE,append=TRUE)
Contents of foo.txt after the above:
"Bar.1" "Bar.2" "Bar.3" "Bar.4"
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Ted.
--------------------------------------------------------------------
E-Mail: (Ted Harding) <Ted.Harding at manchester.ac.uk>
Fax-to-email: +44 (0)870 094 0861
Date: 03-May-10 Time: 23:24:55
------------------------------ XFMail ------------------------------
More information about the R-help
mailing list