1

My question is almost exactly like this one here. But I need the resulting data structure to store matrices or other data types.

With the following code:

> Data <- as.data.frame(matrix(0,nrow = 2, ncol = 5))
> Data
  V1 V2 V3 V4 V5
1 0  0  0  0  0
2 0  0  0  0  0

>Data[2,5] <- matrix(1,nrow = 100, ncol = 100)
Error replacement has 100 row, data has 1

> Data <- as.array(matrix(0,nrow = 2, ncol = 5))
> Data[2,5] <- matrix(1,nrow = 100, ncol = 100)
Error  number of items to replace is not a multiple of replacement length.

I have tried coercing the initial matrix to different types, but the end result is always an error.

I am not attached to any particular data types, but I need an array or n rows and m columns where each item of the array can be any object and I can access this object using a standard lookup such as Data[n,m].

Thank you.

MichaelE
  • 763
  • 8
  • 22

1 Answers1

3

What you need is an array.

A small example to get you started.

data <- array(list(), c(2,5)) # list() will be recycled n*m times
data[2,5] <- list(matrix(1,nrow = 100, ncol = 100))

To access the data in the array, you can use the double brackets [[ like data[[2, 5]]

phiver
  • 23,048
  • 14
  • 44
  • 56
  • Thank you. That was quick and easy. I was trying array from http://www.dummies.com/programming/r/how-to-create-an-array-in-r/ but it never worked normally the key for me was list() which makes it null. Thanks again. – MichaelE Apr 04 '18 at 18:07