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.lmTry this, poke through and see what’s happening:
This is the weird, back-door solution. Create a list, change its class to
data.frame, and then (this is required) set thenamesandrow.namesmanually (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 …)