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