2

This is something that I have been wondering for ages but have never been able to get an answer on.

I am trying to understand how to make a dataframe in R, where each element of the dataframe is itself a vector or a matrix.

For example, let us say we have a regular vector $\vec{V}$ with elements being real numbers $\Bbb R$.

Then to acess any number we would have:

$\vec{V}[3]$ which would give the third element of said vector.

Now, I would like to know how to do this with say a dataframe D, where each element of the dataframe is itself a vector or matrix.

So say that:

$\vec{D}[3]$ is not a real number, but a vector.

How can this be done in R?

Ethan
  • 1,625
  • 8
  • 23
  • 39
Quality
  • 121
  • 4
  • In the tidyverse, see nest() to create list columns, i.e. each element of the column is itself another dataframe. – aranglol Jan 16 '21 at 06:52

2 Answers2

0

This can be done like this:

library(data.table)

dt<-data.table(x=c("a","b","c"), y= lapply(1:3, function(x) matrix(rep(x, x*x), nrow=x)))

dt[2, y]

#[[1]]
#     [,1] [,2]
#[1,]    2    2
#[2,]    2    2

dt[2, `:=`(y=list(c(1,2,3)))]
dt[2,y]

#[[1]]
#[1] 1 2 3


```
Valentas
  • 1,064
  • 1
  • 8
  • 20
-1

Dataframe is a representation of 2 D matrix in R. R does not support MultiIndex dataframes that can represent more complex structures.

Maybe you can model the problem as a Tensor ( https://cran.r-project.org/web/packages/tensorr/vignettes/introduction.html , https://www.rdocumentation.org/packages/rTensor/versions/1.4/topics/Tensor-class)

Shamit Verma
  • 2,239
  • 1
  • 8
  • 14