[R] Questions about readBin function (Was: dec2bin?)

From: Tuszynski, Jaroslaw W. <JAROSLAW.W.TUSZYNSKI_at_saic.com>
Date: Wed 12 Oct 2005 - 22:47:52 EST


Hi,

The latest version of R had some changes to functions "readbin() and writeBin() [which] now support raw vectors as well as filenames and connections.". As a result I am working on retiring "raw2bin" and "bin2raw" functions from "caTools" package which do exactly the same. Thanks to Prof. Ripley for bringing this change to my attention.

Which brings me to my question: how to use readBin function to read the whole file or vector "con" and not just requested number of elements (n) from it? In other words what to do if I do not know what to set argument "n" to ("The (maximal) number of records to be read"), and want to read all records?

So far the simplest solution I found is to measure vector length (or file size) of "con" and set n to length()%/%size. Which gets quite messy if
"size" is not provided and have to be deduced from "what" (see code below).
Am I missing something? Is there an easier way to read the whole file or vector? Shouldn't that be the default?

readBin(con, what, n = 1, size = NA, signed = TRUE, endian = .Platform$endian)

bin2raw = function(x, ...) writeBin(x, raw(), ...) # old bin2raw can be easily written using curent writeBin

raw2bin = function(r, what, size=NA, ...) {
  TypeList = c("logical", "integer", "double", "complex", "character",
"raw",

               "numeric", "int")
  if (!is.character(what) || length(what) != 1 || !(what %in% TypeList))     what <- typeof(what)
  if (!is.vector(r) || mode(r) == "list")     stop("raw2bin: 'r' has to be vector of type 'raw'")   if (what=="raw") return(r)
  if (!is.na(size)) nBits=size
  else nBits = switch(match(typeof(x), TypeList), 4, 4, 8, 16, 2, 1, 8, 4)   n = length(r)
  if (n%%nBits)
    stop("raw2bin: number of elements in 'r' is not multiple of 'size'")   x = readBin(r, what, n = n%/%nBits, size=size, ...)   return (x)
}

 Jarek

====================================================\==== 
 Jarek Tuszynski, PhD.                           o / \ 
 Science Applications International Corporation  <\__,|  
 (703) 676-4192                                   ">  \ 
 Jaroslaw.W.Tuszynski@saic.com                     `   \

______________________________________________
R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Wed Oct 12 22:54:21 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:40:41 EST