简体   繁体   English

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

[英]Transform data frame into matrix: two columns as row and column names

In RI have data structured like this: 在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
...

I would like to convert it to a matrix and then plot it as a graph with number of moves represented by line width. 我想将其转换为矩阵,然后将其绘制为图形,并以线宽表示移动数。 What I need is to reshape the data into something like: 我需要的是将数据重塑为类似的内容:

    1    2    3 ...
1   345  765  923
2   6    23   345
3   954  ...  ...
...

Does anybody have an idea how to do that automatically in R? 有人知道如何在R中自动执行此操作吗? It would be great if it could work not only with numbers in first and second column but also with strings, so that I could have a matrix with this strings as row and column names. 如果它不仅可以与第一和第二列中的数字一起使用,而且还可以与字符串一起使用,那将是很棒的,这样我就可以拥有一个矩阵,其中该字符串作为行和列的名称。

Cheers, P 干杯,P

Using acast is one way to go. 使用Acast是一种方法。 But I like James's way 但是我喜欢詹姆斯的方式

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

HTH 高温超导

Using the data provided by Iselzer, you can use xtabs : 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM