Search code examples
rchord-diagramcirclize

How to transform data from frame/datatable to matrix in R for a Chord Diagram?


This may seem relatively simple, but I'm trying to change data from a data frame into a matrix as I'm working with the new D3 chorddiag package. Before I've used circlize and depended on using the dataframe capabilities. Chorddiag seems to rely solely on matrices so I'm wondering how to jump across the types. Below is the example:

library(circlize)
library(chorddiag)
from = c("A", "A", "A", "A", "B", "B", "C", "C", "D")
to = c("B", "C", "D", "J", "E", "F", "G", "H", "I")
value = c(5,8,2,5,5,6,7,8,11)
food = data.frame(from, to, value)
food
chordDiagram(food)


#now in chordiag how to transform into matrix like m?
m <- matrix(c(11975,  5871, 8916, 2868,
              1951, 10048, 2060, 6171,
              8010, 16145, 8090, 8045,
              1013,   990,  940, 6907),
            byrow = TRUE,
            nrow = 4, ncol = 4)
groupnames <- c("black", "blonde", "brown", "red")
row.names(m) <- groupnames
colnames(m) <- groupnames
chorddiag(m)

How do I change food to resemble m? I thought maybe something like below, but I'm not sure how to add the names in. Appreciate the help

   matrix(data = food$value, nrow = length(food$from), ncol = length(food$to), byrow = TRUE
       #,dimnames = 
       )

Solution

  • As your example:

    > food_matrix <- matrix(data = food$value, nrow = length(food$from), ncol = length(food$to), byrow = TRUE)
    > food_matrix
          [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
     [1,]    5    8    2    5    5    6    7    8   11
     [2,]    5    8    2    5    5    6    7    8   11
     [3,]    5    8    2    5    5    6    7    8   11
     [4,]    5    8    2    5    5    6    7    8   11
     [5,]    5    8    2    5    5    6    7    8   11
     [6,]    5    8    2    5    5    6    7    8   11
     [7,]    5    8    2    5    5    6    7    8   11
     [8,]    5    8    2    5    5    6    7    8   11
     [9,]    5    8    2    5    5    6    7    8   11
    

    Now we name the rows and columns of your matrix with rownames() and colnames()

    > rownames(food_matrix) <- food$from
    > colnames(food_matrix) <- food$to
    > food_matrix
      B C D J E F G H  I
    A 5 8 2 5 5 6 7 8 11
    A 5 8 2 5 5 6 7 8 11
    A 5 8 2 5 5 6 7 8 11
    A 5 8 2 5 5 6 7 8 11
    B 5 8 2 5 5 6 7 8 11
    B 5 8 2 5 5 6 7 8 11
    C 5 8 2 5 5 6 7 8 11
    C 5 8 2 5 5 6 7 8 11
    D 5 8 2 5 5 6 7 8 11`
    

    Is that the output you where looking for?