5

Is it possible to create matrix of vectors in R? I mean the elements of this matrix must be vectors. For example mat[1,3] == c(6,8,9)

i must create 40x40 matrix and i need to fill it manually.

mnel
  • 113,303
  • 27
  • 265
  • 254
trood
  • 121
  • 1
  • 6

2 Answers2

8

This is not a matrix but an array:

myarray <- array(1:24, c(2,4,3))
myarray[1,3,]
#[1]  5 13 21
Roland
  • 127,288
  • 10
  • 191
  • 288
  • i can't use this. i need 40x40 matrix and i need to fill the matrix manually. – trood Nov 26 '12 at 14:29
  • 2
    Of course you can use this. An array is just a higher dimensional extension of the matrix concept and works more or less in the same way. – Roland Nov 26 '12 at 14:44
  • 1
    if this doesn't work for you, it would probably be a good idea to provide a bit more context and explain *why* you can't use this. To fill the array manually as above you would just say `myarray <- array(dim=c(40,40,3)); mat[1,3,] <- c(6,8,9)` and so forth ... – Ben Bolker Nov 26 '12 at 16:30
6

Well, you can add dimensions to a list, so that it resembles a matrix where the elements can be anything you want, including vectors of different length. For example:

foo <- as.list(numeric(2^2))
dim(foo) <- c(2,2)

# Assignment per element:
foo[[1,1]] <- 1:4
foo[[1,2]] <- 1:10
foo[[2,1]] <- "foo"
foo[[2,2]] <- list(foo)

Gives you a weird looking object:

> foo
     [,1]      [,2]      
[1,] Integer,4 Integer,10
[2,] "foo"     List,1    

Where each element basically is a vector. Still, this is hardly ever the best way of doing this. If the vectors are the same length an array as described by Roland is much more appropriate.

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • 3
    If I am right the first line has a bug that can be misleading.. it should be foo <- as.list(numeric(2*2)) for the case of 2 the result is the same but for any other it is different... – Picarus Jun 12 '15 at 01:29