Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matrix of vectors in R

Tags:

arrays

r

matrix

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.

like image 625
trood Avatar asked Nov 26 '12 13:11

trood


2 Answers

This is not a matrix but an array:

myarray <- array(1:24, c(2,4,3))
myarray[1,3,]
#[1]  5 13 21
like image 136
Roland Avatar answered Sep 25 '22 19:09

Roland


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.

like image 24
Sacha Epskamp Avatar answered Sep 25 '22 19:09

Sacha Epskamp