0

This must have a simple solution?! I have a raster-like matrix where the names of rows and columns are the x and y coordinates for the values. I'd like to bring it into a "x,y,z" structure (does not need to be a data frame).

Example and desired output below. In fact, this approach would suffice for my problem at hand, but I am still curious for a scalable approach.

I am aware this is basically a reshape and there are options like reshape2::melt or tidyr::pivot_longer, but I wondered if there is a more matrix specific way to achieve this, in particular with base R

set.seed(42)
foo <- structure(matrix(round(rnorm(16),1), nrow = 4), dimnames=list(seq(0.1,0.4,.1), seq(0.1,0.4,.1)))
foo
#>      0.1  0.2  0.3  0.4
#> 0.1  1.4  0.4  2.0 -1.4
#> 0.2 -0.6 -0.1 -0.1 -0.3
#> 0.3  0.4  1.5  1.3 -0.1
#> 0.4  0.6 -0.1  2.3  0.6

# desired output: 
data.frame(x = rep(seq(0.1,0.4,.1), each = 4), y = rep(seq(0.1,0.4,.1), 4), z = as.numeric(foo))
#>      x   y    z
#> 1  0.1 0.1  1.4
#> 2  0.1 0.2 -0.6
#> 3  0.1 0.3  0.4
#> 4  0.1 0.4  0.6
#> 5  0.2 0.1  0.4
#> 6  0.2 0.2 -0.1
#> 7  0.2 0.3  1.5
#> 8  0.2 0.4 -0.1
#> 9  0.3 0.1  2.0
#> 10 0.3 0.2 -0.1
#> 11 0.3 0.3  1.3
#> 12 0.3 0.4  2.3
#> 13 0.4 0.1 -1.4
#> 14 0.4 0.2 -0.3
#> 15 0.4 0.3 -0.1
#> 16 0.4 0.4  0.6
tjebo
  • 21,977
  • 7
  • 58
  • 94

1 Answers1

1

Use melt from reshape2 to obtain a data frame output:

reshape2::melt(foo)

there are multiple options in r to do this. pivot_longer etc. A google search such as 'converting from wide to long' will result in many solutions.

tjebo
  • 21,977
  • 7
  • 58
  • 94
Ali
  • 1,048
  • 8
  • 19
  • that is certainly an option.+1. I wondered though if there are more matrix specific options to reshape, ideally with base R syntax. I will specify this in the question, thanks for pointing this out – tjebo Mar 20 '21 at 14:59
  • 1
    I accept because you helped me find the pertinent duplicate question. If akrun did not suggest a base R version, I guess reshape2::melt is the way to go. Actually, in this question https://stackoverflow.com/a/26838774/7941188, akrun *does* suggest a base R alternative :) – tjebo Mar 20 '21 at 15:05
  • 1
    Great, `as.data.frame(as.table(m1))` is a nice solution. Good luck! – Ali Mar 20 '21 at 15:23