Convert a matrix to a 1 dimensional array

Viewed 269002

I have a matrix (32X48).

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

11 Answers

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

For anyone looking to produce not just the array, but the array with the corresponding Row and Column names I recommend the melt function as in this answer.

library(reshape2)
df.L <- melt( df, id.vars="New_name4_rownames",
               value.name="NAME_of_VALUE", variable.name="New_name4_colnames" )
print(df.L)

And then you can combine the names of the row and column as you like and use spread/pivot_wider to have the column names be a combination of the row+column names of the matrix and 1 row which is your vector.

df.L$Both <- paste0(df.L$New_name4_rownames, "_", df.L$New_name4_colnames)
df.sel <- df.L[,3:4] #select only values and combined column names
output1d <- pivot_wider(data = df.sel, names_from = Both, values_from = NAME_of_VALUE)
Related