0

这可能看起来相对简单,但我正在尝试将数据从数据帧更改为矩阵,因为我正在使用新的 D3 chorddiag 包。在我使用 circlize 并依赖于使用数据框功能之前。Chorddiag 似乎完全依赖于矩阵,所以我想知道如何跳过这些类型。下面是示例:

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)

如何将食物更改为类似于 m?我想可能像下面这样,但我不知道如何添加名称。感谢帮助

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

1 回答 1

0

作为你的例子:

> 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

现在我们用和命名矩阵的行和rownames()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`

那是你在寻找的输出吗?

于 2017-02-03T16:50:06.187 回答