[R] Example function for reading Octave data files made by "save -ascii"

Stephen Eglen eglen at pcg.wustl.edu
Mon Feb 25 19:56:26 CET 2002


Hi,

I thought I'd post this simple function I wrote, just in case other
users also have Octave data files that they'd like to read into R.
(Octave is a matlab-like language, see www.octave.org for details.)

Any comments/suggestions appreciated.

Stephen


read.oct.file <- function(filename) {

  ## Read in an Octave ASCII data file (as created by "save -ascii" in
  ## Octave 2.x) and return a list of the objects (matrix, string
  ## array or scaler) returned.  Any "_" in the octave name is
  ## converted into "." to avoid confusion in R with _.


  read.oct.matrix <- function(con) {
    ## Helper function: read in a matrix.
    nrows <- as.numeric(substring(readLines(con,1), 9))
    ncols <- as.numeric(substring(readLines(con,1), 12))
    data <- scan(con, nlines=nrows, quiet=T)
    d <- matrix(data, nrow=nrows, ncol=ncols, byrow=T)
    d
  }
  
  read.oct.stringarr <- function(con) {
    ## Helper function: read in a string array.
    elements <- as.numeric(substring(readLines(con,1), 13))
    d <- readLines(con, n=elements*2)
    ## remove the odd-numbered lines, they just store "length".
    d <- d[ seq(from=2, by=2, length=length(d)/2)]
  }
  
  read.oct.scalar <- function(con) {
    ## Helper function: read in a scalar.
    d <- as.numeric(scan(con, nlines=1, quiet=T))
    d
  }


  zz <-  file(filename, "r")
  readLines(zz, n=1)                    #skip over the header line.

  ## Build up a return list of items -- separately store the return values
  ## and the names.
  ret.list <- list()                   
  ret.names <- list()
  reading <- TRUE
  while(reading) {
    name.line <- readLines(zz, 1, ok=TRUE)
    if (length(name.line) == 0) {
      reading <- FALSE
    }
    else {
      name <- substring(name.line, 9)
      name <- gsub("_", ".", name)          #octave vars often have _ in them.
      type <- substring(readLines(zz,1), 9)
      res <- switch(type,
                    "matrix" = read.oct.matrix(zz),
                    "scalar" = read.oct.scalar(zz),
                    "string array" = read.oct.stringarr(zz),
                    stop(paste("data type",type,"not recognised")))
      ##assign(name, res, env = .GlobalEnv)
      ret.list <- c( ret.list, list(res))
      ret.names <- c( ret.names, name)
    }
  }
  close(zz)
  names(ret.list) <- ret.names
  ret.list
}
  






-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list