Re: [R] Java parser for R data file?

From: David Coppit <david_at_incogen.com>
Date: Thu, 6 Dec 2007 11:12:43 -0800

On 12/5/07 12:15 PM, "Prof Brian Ripley" <ripley_at_stats.ox.ac.uk> wrote:

On Wed, 5 Dec 2007, David Coppit wrote:

> Or, given that I'm dealing with just a single array, would it be better to
> roll my own I/O using write.table or write.matrix from the MASS package?

It would be much easier. The save() format is far more complex than you need. However, I would use writeBin() to write a binary file and read that in in Java, avoiding the binary -> ASCII -> binary conversion.

Thanks for the suggestion-writeBin works quite well. For posterity, here's what I did:

On the R side:

# Assumes that there are no special values in the tofList, such as NA_REAL, # R_PosInf, R_NegInf, ISNAN, R_FINITE. See the "R Data Import/Export" manual. saveListAsBinary <- function( tofList, filename ) {
  outConn <- file( filename, "wb" );

  for (m in 1:length(tofList)) {

    writeBin(names(tofList)[[m]], outConn);
    writeBin(length(tofList[[m]]), outConn, size = 4, endian = "big");
    writeBin(tofList[[m]], outConn, size = 4, endian = "big");
  }

  close(outConn);
}

saveListAsBinary(myList, "outfile.RDat");

On the Java side:

  public static void read_R_Output(String filename, ArrayList<String> names,

      ArrayList<ArrayList<Float>> data)
  {
    try {

      DataInputStream dataInputStream = new DataInputStream(
        new BufferedInputStream(new FileInputStream(filename)));

      boolean endOfFile = false;

      while (!endOfFile) {
        try {
          StringBuffer sb = new StringBuffer();

          byte c;
          while ((c = dataInputStream.readByte()) != 0)
            sb.append((char)c);

          names.add(new String(sb));

          int cols = dataInputStream.readInt();

          ArrayList<Float> row = new ArrayList<Float>(cols);

          for (int i = 0; i < cols; i++)
            row.add(dataInputStream.readFloat());

          data.add(row);
        } catch (EOFException e) {
          endOfFile = true;
        }
      }

      dataInputStream.close();
    } catch (Exception e) {
      e.printStackTrace();

    }
  }

Regards,
David

        [[alternative HTML version deleted]]



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. Received on Thu 06 Dec 2007 - 20:29:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 06 Dec 2007 - 20:30:18 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.