Niro Mal
Niro Mal

Reputation: 117

Reading a .mat file using R

I'm trying to read a .mat file using R.

library(R.matlab)
data <- readMat('e-060RAW.mat')

It gives me this error.

Error in readMat5(con, firstFourBytes = firstFourBytes, maxLength = maxLength) : 
  Reading of MAT v7.3 files is not supported. If possible, save the data in MATLAB using 'save -V6'.

How am I supposed to get this sorted out. Is there any other way to read a .mat file using R.

Upvotes: 2

Views: 4231

Answers (2)

Dieter.Wilhelm
Dieter.Wilhelm

Reputation: 555

Reading .mat (V7.3, matlab >= 2006b) files using the hdf5r package

 ## install.packages("hdf5r")
  library(hdf5r)
  ## ######################################################################
  ## create an hdf5 file
  test_file <- tempfile(fileext=".h5")
  file.h5 <- H5File$new( test_file, mode="w")

  data(cars)
  cars
  file.h5$create_group("test")
  file.h5[["test/cars"]] <- cars
  cars_ds <- file.h5[["test/cars"]]
  cars_ds
  h5attr(cars_ds, "rownames") <- rownames(cars)

  ## Close the file at the end
  ## the 'close' method closes only the file-id, but leaves object inside the file open
  ## This may prevent re-opening of the file. 'close_all' closes the file and all objects in it
  file.h5$close_all()

  ## read and investigate the hdf5 file
  file.h5 <- H5File$new(test_file, mode="r+")

  ## lets look at the content
  file.h5$ls(recursive=TRUE)

  cars_ds <- file.h5[["test/cars"]]
  ## note that for now tables in HDF5 are 1-dimensional, not 2-dimensional
  mycars <- cars_ds[]
  h5attr_names(cars_ds)
  h5attr(cars_ds, "rownames")

  file.h5$close_all()

Upvotes: 0

nekomatic
nekomatic

Reputation: 6284

From https://www.rdocumentation.org/packages/R.matlab/versions/3.6.2/topics/readMat:

MAT v7.3 files, saved using for instance save('foo.mat', '-v7.3'), stores the data in the Hierarchical Data Format (HDF5) [6, 7], which is a format not supported by this function/package. However, there exist other R packages that can parse HDF5, e.g. CRAN package h5 and Bioconductor package rhdf5.

Upvotes: 2

Related Questions