[R] Writing - specyfic format

Earl F. Glynn efg at stowers-institute.org
Thu Jun 28 17:27:09 CEST 2007


"jastar" <mswierniak at o2.pl> wrote in message 
news:11341784.post at talk.nabble.com...
>
> Hi all,
> I have a trouble - I need to write file in a very specyfic format.
> I have two vectors which different lengths and one data.frame (or matrix).
> I want to write it to "*.txt" file in following way:
> 1st row of file is my 1st vector (separate by spacebar)
> 2nd row of file is 2nd vector (also separate by spacebar)
> Rest of this file should be a matrix with elements separated by tab.
> For example: a=1, 2, 3, b=4, 5, c=[1, 2, 3, 4, 5, 6;
>                                            7, 8, 9, 10, 11, 12,]
> and I want to have file (it have to be .txt file) like:
> 1 2 3
> 4 5
> 1     2     3     4     5     6
> 7     8     9     10   11    12
>
> This thing have to be done automaticly from R.
> Is it possible?

Try this:

a <- 1:3
b <- 4:5
c <- matrix(1:12, 2,6, byrow=TRUE)

outFile <- file("SpecificFormat.txt", "w")
cat(paste(a, sep=" "), "\n", file=outFile)
cat(paste(b, sep=" "), "\n", file=outFile)

for (j in 1:nrow(c))
{
  cat(paste(c[j,], collapse="\t"), "\n", file=outFile)
}

close(outFile)


Resulting output file (with spaces or tabs as specified):
1 2 3
4 5
1 2 3 4 5 6
7 8 9 10 11 12


[But I normally avoid tabs since you cannot "see" them easily with many 
editors.]

efg

Earl F. Glynn
Stowers Institute for Medical Research



More information about the R-help mailing list