将数据帧转换为矩阵:两列作为行名和列名

two*_*owo 1 r graph matrix

RI中的数据结构如下:

Ref  Url   Moves
1    1     345
1    2     765
1    3     923
1    4     233
2    1     6
2    2     23
2    3     345
2    4     354
3    1     954
...
Run Code Online (Sandbox Code Playgroud)

我想将其转换为矩阵,然后将其绘制为具有由线宽表示的移动数量的图形.我需要的是将数据重塑为以下内容:

    1    2    3 ...
1   345  765  923
2   6    23   345
3   954  ...  ...
...
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何在R中自动执行此操作?如果它不仅可以在第一列和第二列中使用数字而且还可以使用字符串,那将是很好的,因此我可以使用此字符串作为行和列名称的矩阵.

干杯,P

Luc*_*zer 6

使用acast是一种方法.但我喜欢詹姆斯的方式

library(reshape2)
dd <- read.table(header = T, textConnection("Ref  Url   Moves
 1    1     345
 1    2     765
 1    3     923
 1    4     233
 2    1     6
 2    2     23
 2    3     345
 2    4     354
 3    1     954"))

acast(dd, Ref ~ Url)
Using Moves as value column: use value_var to override.
    1   2   3   4
1 345 765 923 233
2   6  23 345 354
3 954  NA  NA  NA
Run Code Online (Sandbox Code Playgroud)

HTH


Jam*_*mes 6

使用Iselzer提供的数据,您可以使用xtabs:

xtabs(Moves~Ref+Url,dd)
   Url
Ref   1   2   3   4
  1 345 765 923 233
  2   6  23 345 354
  3 954   0   0   0
Run Code Online (Sandbox Code Playgroud)