-2

old matrix with LULC (land use land change) data

Water Trees Building
Water 20 80 60
Second 70 10 10
Building 10 10 30

To this is what I want it to look like Thank you

Value
Water-Water 20
Water-Trees 70
Water-Building 10
Trees-Trees 10
Trees-Water 80
Trees-Building 10
Building-Water 10
Building-Trees 10
Building-Building 30
  • 1
    If the question this is marked as a duplicate of doesn't answer your question, it will be because you have row names that are being dropped. If you're using `data.table` set `keep.rownames = TRUE` and if you're using `tidyverse` use the `rownames_to_column()` function. If the output is still not as expected, edit your question to include a [`reproducible example`](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of your data, e.g. using `dput(head(df))`. – SamR Mar 23 '23 at 08:39

1 Answers1

0
m <- matrix(c(20, 70, 10, 80, 10, 10, 60, 10, 30), 3, 3, dimnames = list(c("Water","Trees","Building"), c("Water","Trees","Building")))
            
library(tidyverse)

m %>% 
  as.data.frame.table %>%
  summarize(
    group = paste(Var1, Var2, sep = "-"),
    Value = Freq
  ) %>%
  column_to_rownames("group") %>%
  as.matrix # if you want the output to be a matrix again

                  Value
Water-Water          20
Trees-Water          70
Building-Water       10
Water-Trees          80
Trees-Trees          10
Building-Trees       10
Water-Building       60
Trees-Building       10
Building-Building    30

 num [1:9, 1] 20 70 10 80 10 10 60 10 30
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:9] "Water-Water" "Trees-Water" "Building-Water" "Water-Trees" ...
  ..$ : chr "Value"
Merijn van Tilborg
  • 5,452
  • 1
  • 7
  • 22