[R] Moving data between R and Matlab back and forth?

Tribo Laboy tribolaboy at gmail.com
Wed Mar 26 17:27:38 CET 2008


Hi to the list,

I am trying to find a way to painlessly move structured data back and
forth between R and Matlab (also Octave). For this purpose I found the
R.matlab package great help. I wish to use a Matlab -v6 MAT file as an
intermediary format, because it is well read by both Matlab and
Octave. It is also well read by 'readMat' function in R.matlab
package, but that is where I run into problems because of poor
knowledge of R.

By structured data I mean data in data frames in R and the closest
equivalent - structures in Matlab. Here is what I have done.

-----------------------------------------------------
Make a data frame in R and export it
-----------------------------------------------------

> Maker <- factor(c("HP", "HP", "Sony", "DELL", "whitebox", "whitebox"))
> CPUspeed <- c(2,4,2.5,2.5,2,5)
> HDD <- c(80, 250, 100, 100, 80, 300)
> RAM <- c(2, 2, 1, 2, 2, 4)
> labpc <- data.frame(Maker, CPUspeed, HDD, RAM)

> labpc
     Maker CPUspeed HDD RAM
1       HP      2.0  80   2
2       HP      4.0 250   2
3     Sony      2.5 100   1
4     DELL      2.5 100   2
5 whitebox      2.0  80   2
6 whitebox      5.0 300   4

> library(R.matlab)
> writeMat("labpc.mat", labpcdata = labpc)
--------------------------------------------------------------

--------------------------------------------------------------
In MATLAB - everything is as expected
--------------------------------------------------------------
load('labpc.mat')

>> labpcdata

labpcdata =

       Maker: {6x1 cell}
    CPUspeed: [6x1 double]
         HDD: [6x1 double]
         RAM: [6x1 double]

>> class(labpcdata)

ans =

struct

>> labpcstruct = labpcdata
>> save('labpcstruct.mat', 'labpcstruct')
---------------------------------------------------------


-------------------------------------------------------
Back in R - how to rebuild the data frame from the list labpcstruct?
-------------------------------------------------------
> labpcfile <- readMat("labpcstruct.mat")
> labpcfile
$labpcstruct
, , 1

         [,1]
Maker    List,6
CPUspeed Numeric,6
HDD      Numeric,6
RAM      Numeric,6


attr(,"header")
attr(,"header")$description
[1] "MATLAB 5.0 MAT-file, Platform: PCWIN, Created on: Wed Mar 26
15:49:21 2008                                                  "

attr(,"header")$version
[1] "5"

attr(,"header")$endian
[1] "little"

> labpcstruct <- labpcfile$labpcstruct
> labpcstruct
, , 1

         [,1]
Maker    List,6
CPUspeed Numeric,6
HDD      Numeric,6
RAM      Numeric,6


> typeof(labpcstruct)
[1] "list"

--------------------------------------------

So if there is any kind soul that will tell me how to get back the
original data frame from the imported list 'labpcstruct', that would
be great.

Regards,

TL



More information about the R-help mailing list