[R] Moving data between R and Matlab back and forth?
Tribo Laboy
tribolaboy at gmail.com
Thu Mar 27 10:13:10 CET 2008
I have packaged the above posted code as a function and I am posting
it here in case someonw would find it useful in the future.
--------------function begin -------------------------
readMat2df <- function(readfiledata, datastr){
tmpdata <- readfiledata[[datastr]] # use the string contained in
'datastr' to acccess the data with that name
tmpdata <- drop(tmpdata) # Drops all the unnecessary indexes with
length 1 and the list becomes much simpler
# If any of the contents of each cell is a list then "rbind" its
elements into a single vector and treat it as a factor
# These elements were represented as cell elements of a cell array
in the MATLAB structure.
for (k in 1:length(tmpdata)){
if (mode(tmpdata[[k]]) == "list") {
tmpdata[[k]]<- as.factor(do.call("rbind", tmpdata[[k]]))
}
}
tmpdf <- as.data.frame(tmpdata)
return(tmpdf)
}
------------------function end --------------------------------
How to use this thing?
Well suppose you had an R data frame and exported it into Matlab MAT
v6 format with 'writeMat' function of R.matlab like this:
library(R.matlab)
writeMat("labpc.mat", labpcexport = labpc) #This give the name
'labpcexport' to the ML structure holding the data
Re-load the file in R with 'readMat' like this
labpcfile <- readMat("labpc.mat")
To get back a data frame from the imported MAT file:
1. Find the name of the variable that holds it. To get of all the
variables that were in the MAT file:
names(labpcfile)
2. Pass this name and the name of the list that holds all imported
MAT data to the function, get a data frame out:
myFavoriteDataFrame <- readMat2df(labpcfile, " labpcexport")
Hope this is useful for someone.
Regards,
TL
More information about the R-help
mailing list