Convert a matrix to a 1 dimensional array

后端 未结 10 1470
忘了有多久
忘了有多久 2020-11-27 14:45

I have a matrix (32X48).

How can I convert the matrix into a single dimensional array?

相关标签:
10条回答
  • 2020-11-27 15:08

    If we're talking about data.frame, then you should ask yourself are the variables of the same type? If that's the case, you can use rapply, or unlist, since data.frames are lists, deep down in their souls...

     data(mtcars)
     unlist(mtcars)
     rapply(mtcars, c) # completely stupid and pointless, and slower
    
    0 讨论(0)
  • 2020-11-27 15:12

    You can use Joshua's solution but I think you need Elts_int <- as.matrix(tmp_int)

    Or for loops:

    z <- 1 ## Initialize
    counter <- 1 ## Initialize
    for(y in 1:48) { ## Assuming 48 columns otherwise, swap 48 and 32
    for (x in 1:32) {  
    z[counter] <- tmp_int[x,y]
    counter <- 1 + counter
    }
    }
    

    z is a 1d vector.

    0 讨论(0)
  • 2020-11-27 15:16

    From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

    Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
    dim(Elts_int) <- (maxrow_int*maxcol_int,1)
    
    0 讨论(0)
  • 2020-11-27 15:19

    It might be so late, anyway here is my way in converting Matrix to vector:

    library(gdata)
    vector_data<- unmatrix(yourdata,byrow=T))
    

    hope that will help

    0 讨论(0)
  • 2020-11-27 15:23

    try c()

    x = matrix(1:9, ncol = 3)
    
    x
         [,1] [,2] [,3]
    [1,]    1    4    7
    [2,]    2    5    8
    [3,]    3    6    9
    
    c(x)
    
    [1] 1 2 3 4 5 6 7 8 9
    
    0 讨论(0)
  • 2020-11-27 15:28

    Either read it in with 'scan', or just do as.vector() on the matrix. You might want to transpose the matrix first if you want it by rows or columns.

    > m=matrix(1:12,3,4)
    > m
         [,1] [,2] [,3] [,4]
    [1,]    1    4    7   10
    [2,]    2    5    8   11
    [3,]    3    6    9   12
    > as.vector(m)
     [1]  1  2  3  4  5  6  7  8  9 10 11 12
    > as.vector(t(m))
     [1]  1  4  7 10  2  5  8 11  3  6  9 12
    
    0 讨论(0)
提交回复
热议问题