To get a data.frame
with 1 row and 2 columns for the given example you have to put the matrix
inside a list
.
m <- matrix(1:4, 2)
x <- list2DF(list(id=1, mat=list(m)))
x
# id mat
#1 1 1, 2, 3, 4
str(x)
#'data.frame': 1 obs. of 2 variables:
# $ id : num 1
# $ mat:List of 1
# ..$ : int [1:2, 1:2] 1 2 3 4
y <- data.frame(id=1, mat=I(list(m)))
y
# id mat
#1 1 1, 2, 3, 4
str(y)
#'data.frame': 1 obs. of 2 variables:
# $ id : num 1
# $ mat:List of 1
# ..$ : int [1:2, 1:2] 1 2 3 4
# ..- attr(*, "class")= chr "AsIs"
To create a data.frame
with a column containing a matrix
, with the given data with 2 rows and 2 columns, directly when creating the data.frame
using I()
will be straight forward. An alternative without AsIs
could be to insert it later, as already shown by others.
m <- matrix(1:4, 2)
x <- data.frame(id=1, mat=I(m))
str(x)
'data.frame': 2 obs. of 2 variables:
$ id : num 1 1
$ mat: 'AsIs' int [1:2, 1:2] 1 2 3 4
y <- data.frame(id=rep(1, nrow(m)))
y[["m"]] <- m
#y["m"] <- m #Alternative
#y[,"m"] <- m #Alternative
#y$m <- m #Alternative
str(y)
#'data.frame': 2 obs. of 2 variables:
# $ id: num 1 1
# $ m : int [1:2, 1:2] 1 2 3 4
z <- `[<-`(data.frame(id=rep(1, nrow(m))), , "mat", m)
str(z)
#'data.frame': 2 obs. of 2 variables:
# $ id : num 1 1
# $ mat: int [1:2, 1:2] 1 2 3 4
Alternatively the data can be stored in a list
.
m <- matrix(1:4, 2)
x <- list(id=1, mat=m)
x
#$id
#[1] 1
#
#$mat
# [,1] [,2]
#[1,] 1 3
#[2,] 2 4
str(x)
#List of 2
# $ id : num 1
# $ mat: int [1:2, 1:2] 1 2 3 4