在R中包含一个矩阵的列的data.frame [英] data.frame with a column containing a matrix in R

查看:114
本文介绍了在R中包含一个矩阵的列的data.frame的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  m<  -  matrix( c(1,2,3,4),nrow = 2,ncol = 2)
df< - data.frame(id = 1,mat = m)

但是当我这样做时,我得到一个2行和3列数据帧,而不是一个数据帧,其中有1行和2列。



阅读文档,我必须使用I()逃离我的矩阵。

  df <  -  data.frame(id = 1,mat = I(m))

str(df)
'data.frame':2 obs。的2个变量:
$ id:num 1 1
$ mat:AsIs [1:2,1:2] 1 2 3 4

据我所知,数据框包含矩阵每行的一行,而mat域是矩阵列值的列表。



因此,如何获取包含矩阵的数据框?



谢谢!

解决方案

我发现包含矩阵的数据框架令人难以置信,但是,我知道实现这一点的唯一方法是隐藏在 stats ::: simulate.lm



尝试这一点,看看发生了什么:

 code> d<  -  data.frame(y = 1:5,n = 5)
g0 < - glm(cbind(y,ny)〜1,data = d,family =
debug(stats ::: simulate.lm)
s< - simulate(g0,n = 5)

这是一个奇怪的后门解决方案。创建列表,将其类别更改为 data.frame ,然后(这是必需)设置名称 row.names 手动(如果您没有做最后的步骤数据仍将在对象中,但它会打印出来,就好像它有零行...)

  m1 < - 矩阵(1:10,ncol = 2)
m2 < - matrix(5:14,ncol = 2)
dd< - list(m1,m2)
class(dd)< - data.frame
names )< - LETTERS [1:2]
row.names(dd)< - 1:5
dd


I'm trying to put some matrices in a dataframe in R, something like :

m <- matrix(c(1,2,3,4), nrow=2, ncol=2)
df <- data.frame(id=1, mat=m)

But when I do that, I get a dataframe with 2 rows and 3 columns instead of a dataframe with 1 row and 2 columns.

Reading the documentation, I have to escape my matrix using I().

df <- data.frame(id=1, mat=I(m))

str(df)
'data.frame':   2 obs. of  2 variables:
 $ id : num  1 1
 $ mat: AsIs [1:2, 1:2] 1 2 3 4

As I understand it, the dataframe contains one row for each row of the matrix, and the mat field is a list of matrix column values.

Thus, how can I obtain a dataframe containing matrices ?

Thanks !

解决方案

I find data.frames containing matrices mind-bendingly weird, but: the only way I know to achieve this is hidden in stats:::simulate.lm

Try this, poke through and see what's happening:

d <- data.frame(y=1:5,n=5)
g0 <- glm(cbind(y,n-y)~1,data=d,family=binomial)
debug(stats:::simulate.lm)
s <- simulate(g0,n=5)

This is the weird, back-door solution. Create a list, change its class to data.frame, and then (this is required) set the names and row.names manually (if you don't do those final steps the data will still be in the object, but it will print out as though it had zero rows ...)

m1 <- matrix(1:10,ncol=2)
m2 <- matrix(5:14,ncol=2)
dd <- list(m1,m2)
class(dd) <- "data.frame"
names(dd) <- LETTERS[1:2]
row.names(dd) <- 1:5
dd

这篇关于在R中包含一个矩阵的列的data.frame的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆