[R] Reading single precision floats from binary file

Prof Brian Ripley
2001-02-15T17:56:06Z

> Date: Thu, 15 Feb 2001 17:04:48 +0100 (MET)
> From: Kjetil Kjernsmo <kjetil.kjernsmo at astro.uio.no>
> To: R Help list <r-help at stat.math.ethz.ch>
> Subject: [R] Reading single precision floats from binary file
>
> Dear all,
>
> I have a few files with binary data written by a C program a friend wrote.
> I allready have program to read these files, Thomas Lumley and Prof Brian
> D Ripley was kind enough to respond to a question to this list earlier
> with some code that works perfectly, so this is really no problem, it is
> more out curiousity.
>
> Most of my files consists of 40000 single precision floats, and I figured
> the new readBin() function exists for the purpose of reading such files,
> so I tried to use it, but with no success.
>
> Now, the docs say that what you can read is "numeric",
"double",
> "integer", "int", "logical",
"complex", "character", and since "single" is
> not on the list, is it simply not the right tool for the job?

R does not have a "single" mode for vectors, and that is what it says
you can
specify as `what'.

> I tried different things, among them, providing single as what,
> changing the size, etc, but it always ends up with reading 20000 records,
> indicating that it does read the file as double precision floats.
>
> It is not clear to me what the last sentence in the notes for this
> function means, and indeed not quite clear what the function does at all,
> but I was hoping someone can enlighten me.

It is indeed what readBin is for, and for me

readBin(con, "double", n=40000, size=4)

works.  Indeed, there are examples of this in the help page for readBin.

Test:

zz <- file("testbin", "wb")
writeBin(rnorm(20000), zz, size=4)
close(zz)
system("ls -l testbin") # 80000
zz <- file("testbin", "rb")
a <- readBin(zz, numeric(), n = 20000, size=4)
length(a) # 20000
close(zz)


--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595