Convert matrix data to X,Y,Z dataframe

Hello All,
Is there a package to convert a matrix data frame to a dataframe with X,Y,Z columns. i wanted to make the dataframe so that i can use it plot as a scatter ( bubble) plot.

eg convert matrix of this form to
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 534 0 0 0 0 0 0 0 0
[2,] 2 0 0 0 0 0 0 0 0
[3,] 10 17 0 0 0 0 0 0 0
[4,] 8 2 0 0 0 0 0 0 0
[5,] 14 2 17 0 0 0 0 0 0
[6,] 0 2 1 0 0 0 0 0 0

x y Z
1 1 534
1 2 2
1 3 10
1 4 8
1 5 4
1 6 ..
..
2 1
2 2
Thanks
Lalit

Hi Lalit - welcome!
One way to convert a matrix into a data.frame is via the function melt in the reshape package. In order to get the data.frame output that you require, you have to set the names of the rows and columns of the matrix with numbers.

library("reshape2")

mymatrix <- structure(c(534, 2, 10, 8, 14, 0, 0, 0, 17, 2, 2, 2, 0, 0, 0, 
0, 17, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(6L, 
9L), .Dimnames = list(NULL, NULL))
 
dimnames(mymatrix) <- list(x = 1:6, y = 1:9) # Give names to each row and column as well as names of each dimension of the matrix itself.

mydf <- melt(mymatrix)
names(mydf) <- c("x", "y", "Z")  # Rename the columns as per your expected output
head(mydf)
#>   x y   Z
#> 1 1 1 534
#> 2 2 1   2
#> 3 3 1  10
#> 4 4 1   8
#> 5 5 1  14
#> 6 6 1   0

Created on 2020-02-04 by the reprex package (v0.3.0)

1 Like

Thank you !!! this works. I have a follow up question which i will try before posting.

Thank you so much for your quick help !!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.