[R] write output in a custom format

jim holtman jholtman at gmail.com
Thu Feb 14 17:49:09 CET 2008


Here is a start.  You basically have to interate through your data and
use 'cat' to write it out:

particle <- list(dose=c(1,100.0,0),pos=data.frame(x=c(0,1,0,1),y=c(0,1,0,1)))
output <- file("/tempxx.txt", "w")
cat(particle$dose, "\n", file=output, sep=" ")
for (i in 1:nrow(particle$pos)){
    cat(particle$pos$x[i], particle$pos$y[i], "\n", file=output, sep=" ")
}
cat("#\n", file=output, sep=" ")
close(output)

Here is what the file looks like:

1 100 0
0 0
1 1
0 0
1 1
#


On 2/14/08, baptiste Auguié <ba208 at exeter.ac.uk> wrote:
> Hi,
>
>
> I need to create a text file in the following format,
>
> > 1 100.0 0
> >  0 0
> >  1 1
> >  0 0
> >  1 1
> > #
> > 1 100.0 0
> >  0 0
> >  0 1
> >  1 0
> >  1 1
> ...
>
> where # is part of the format and not a R comment.
>
> Each block (delimited by #) consists of a first line with three
> values, call it dose, and a list of (x,y) coordinates which are a
> matrix or data.frame,
>
>
> > particle <- list(dose=c(1,100.0,0),pos=data.frame(x=c(0,1,0,1),y=c
> > (0,1,0,1)))
> >
> > print(particle)
>
>
>
> I'd like to establish a connection to a file and append to it a
> "particle" block in the format above, or even write the whole file at
> once.
>
> Because different lines have a different number of elements, I
> couldn't get write.table to work in this case, and my attempts at sink
> (), dump(), writeLines(), writeChar() all turn into really dirty
> solutions. I have this feeling I'm overlooking a simple solution.
>
> Any help welcome,
>
>
> baptiste
>
> _____________________________
>
> Baptiste Auguié
>
> Physics Department
> University of Exeter
> Stocker Road,
> Exeter, Devon,
> EX4 4QL, UK
>
> Phone: +44 1392 264187
>
> http://newton.ex.ac.uk/research/emag
> http://projects.ex.ac.uk/atto
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>


-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list