how to import a matlab table in R

你说的曾经没有我的故事 提交于 2019-12-11 10:17:39

问题


I have a matlab .mat file with table data type which I want to import in R. I am using 'readMat' for this and R is reading it as a List.

After that is there a way to convert the list into either a dataframe or table format in R? When I use as.dataframe I get the following error :

Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE,  : 
  arguments imply differing number of rows: 5, 6, 1

A possible workaround I thought of is to export the table as a .csv from matlab and read it into R. But this solution does not work for me as some columns in the table are 1x700 arrays and in the CSV each these columns get expanded to 700 columns.

So my question is that is there a direct or indirect way to import a MATLAB table in R?


回答1:


I believe that the best solution is to export the table from MATLAB as a CSV file, as you suggested.

Regarding the size of the certain columns being 1*700 arrays, I would recommend reshaping your data in a tidy way - where each column represents a variable, and each row represents an observation. Is each of your 700 columns of the 1X700 array a different variable, or is it a different value of the same variable, perhaps at a different timestamp? My guess is that you can split these arrays to a 700X1 array, and add an identification to the relevant row in the table data, using foreign keys to connect each new row to an existing row in the table.

This concept of "tidy data" is used less in MATLAB, where it is common to use row vectors to represent data, but is much more accepted in R (see the "tidyverse" packages for more about this).

In MATLAB, split each of the 1X700 arrays to 700X2 vectors - one column will be the foreign key - the identification of the row at the data table, and the second columns should be the value of your variable. If you have n observations in your original data, you should have now an array of size (nX700, 2). Save this array as a table as well. Assuming you now have in MATLAB two tables (your original table and your reshaped data), export them as CSV using writetable:

writetable(table_1, 'table_1.csv')
writetable(table_2, 'table_2.csv')

Then, in R, read the tables using read_csv:

table_1 <- read_csv('table_1.csv')
table_2 <- read_csv('table_2.csv')

Hopes this helps.



来源:https://stackoverflow.com/questions/51243524/how-to-import-a-matlab-table-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!