shutch
shutch

Reputation: 197

R programming - How to create a 2 dimensional array of vectors which are of different lengths

I'm new to the R programming language, and I'm struggling to find the correct data type.

How do you create a matrix of vectors? Maybe a better way to describe this would be a 2 dimensional array of vectors which are of different lengths. This is what I'm trying to do:

    A = c(1, 2, 3, 4)
    B = c(5, 6, 7)

    C = c(10, 11, 12, 13)
    D = c(14, 15, 16)

    E = c(21, 22, 23, 24)
    F = c(25, 26, 27)

    mat = matrix(nrow=3, ncol=2)

    #This code does not work, but it may give you the gist of what I'm trying to do
    mat[1, 1] = A
    mat[1, 2] = B
    mat[2, 1] = C
    mat[2, 2] = D
    mat[3, 1] = E
    mat[3, 2] = F

I would like to get mat to contain the following:

            [,1]         [,2]
    [1,]   1 2 3 4       5 6 7
    [2,]   10 11 12 13   14 15 16
    [3,]   21 22 23 24   25 26 27

I'm sure this is because I'm using the wrong data type, but I can't find the appropriate one. I've tried lists, arrays, and data frames, but none of them seem to quite fit exactly what I'm trying to do. Thanks for your help!

Upvotes: 10

Views: 60965

Answers (2)

IRTFM
IRTFM

Reputation: 263311

I agreeing with MrFlick that this seems hackish, but I had already done something similar. I wonder if there is any regularity that would allow you to make a more compact structure.

 A = list(c(1, 2, 3, 4))
     B = list(c(5, 6, 7))

     C = list(c(10, 11, 12, 13))
     D = list(c(14, 15, 16))

     E = list(c(21, 22, 23, 24))
     F = list(c(25, 26, 27))

     mat = matrix(list(), nrow=3, ncol=2)
     mat[1, 1] = A
     mat[1, 2] = B
     mat[2, 1] = C
     mat[2, 2] = D
     mat[3, 1] = E
     mat[3, 2] = F
 mat
    [,1]      [,2]     
[1,] Numeric,4 Numeric,3
[2,] Numeric,4 Numeric,3
[3,] Numeric,4 Numeric,3
 mat[1,1]
[[1]]
1] 1 2 3 4

If all the columns are in the matrix are each of the same length then it might be easier to work with (and display ) a list of two matrices.

 mlist <- list(fours = do.call(rbind, mat[,1]),
                threes= do.call(rbind, mat[,2]) )
 mlist
# -----------
$fours
     [,1] [,2] [,3] [,4]
[1,]    1    2    3    4
[2,]   10   11   12   13
[3,]   21   22   23   24

$threes
     [,1] [,2] [,3]
[1,]    5    6    7
[2,]   14   15   16
[3,]   25   26   27

Upvotes: 1

MrFlick
MrFlick

Reputation: 206187

You could make a matrix of lists. That would look like

mat<-matrix(list(), nrow=3, ncol=2)
mat[[1,1]] <- c(1, 2, 3, 4)
mat[[1,2]] <- c(5, 6, 7)
mat[[2,1]] <- c(10, 11, 12, 13)
mat[[2,2]] <- c(14, 15, 16)
mat[[3,1]] <- c(21, 22, 23, 24)
mat[[3,2]] <- c(25, 26, 27)

Notice that you have to use double brackets here to extract cells unlike a standard matrix. Also they may not necessarily work the way you expect with standard functions for matrices.

Upvotes: 8

Related Questions