如何将 MATLAB 结构加载到 R 数据框中? [英] How to load a MATLAB struct into a R data frame?
问题描述
我有一个 MATLAB 结构体,其中包含多个字段,这些字段共同描述了多个变量的 100 个观察值,如下(MATLAB 输出):
I have a MATLAB struct, containing a number of fields which together describe, say, 100 observations of a number of variables, as follows (MATLAB output):
mystruct =
fieldA: [100x1 double]
fieldB: [100x1 double]
fieldC: [100x1 double]
fieldD: [100x1 char]
fieldE: {100x1 cell}
我想对这些数据使用 R,所以我将结构保存为 .mat 文件.并使用 R.matlab 包导入它.因为我是 R 的新手,以下内容可能很笨拙,但我可以很好地访问各个字段(R 代码):
I want to use R with this data, so I save the struct as a .mat file. and import it using the R.matlab package. Because I'm new to R, the following is likely clumsy, but I can access individual fields just fine (R code):
> f = readMat('myfile.mat')
> data = f$mystruct
> data
, , 1
[,1]
fieldA Numeric,100
fieldB Numeric,100
fieldC Numeric,100
fieldD Character,100
fieldE List,100
> data = data[, , 1]
> df <- data.frame(fieldA = data$fieldA, fieldB = data$fieldB)
好的,那么问题来了:如何概括上述内容,以便为原始结构中的任意数量的字段生成数据框?对于我的 5-field 示例,我可以手动完成,但是我的下一个数据集有很多字段,我不想全部输入.
OK, so here is the question: how can I generalize the above so that a data frame is generated for an arbitrary number of fields in the original struct? For my 5-field example I can manually do it, but the next data set I have has many fields, and I don't want to enter them all.
根据这个问题,我尝试了rbind()
和 ldply()
,它们构建了超大尺寸的数据框(分别为 1 个变量的 401 个 obs 和 105 个变量的 401 个 obs).
As per this question, I tried rbind()
and ldply()
, which construct outrageously dimensioned data frames (401 obs of 1 variable and 401 obs of 105 variables respectively).
推荐答案
事实证明,MATLAB 元胞数组 (fieldE
) 是作为嵌套列表导入的.使用 unlist
可以解决这个问题:
As it turns out, the MATLAB cell array (fieldE
) was imported as a nested list. Using unlist
takes care of the problem:
data = lapply(data, unlist, use.names=FALSE)
df <- as.data.frame(data) # now has correct number of obs and vars
感谢@koekenbakker 提供对此的关键指针!
Thanks @koekenbakker for the critical pointer to this!
这篇关于如何将 MATLAB 结构加载到 R 数据框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!