将数据框转换为矩阵:两列作为行名和列名 [英] Transform data frame into matrix: two columns as row and column names

查看:701
本文介绍了将数据框转换为矩阵:两列作为行名和列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在RI有这样的数据结构:

 引用网址移动
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
...

我想将它转换为矩阵,然后绘制它作为以线宽表示的移动次数的图表。
我需要的是将数据重塑为如下形式:

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

有人知道如何在R中自动执行该操作吗?如果它不仅可以处理第一列和第二列中的数字,而且还可以处理字符串,那么这将非常棒,因此我可以将这些字符串作为行和列名称使用。



干杯,
P

解决方案

使用acast是一种方法。但我喜欢James的方式

  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)
使用Move作为值列:使用value_var覆盖。
1 2 3 4
1 345 765 923 233
2 6 23 345 354
3 954不适用不适用

HTH


In R I have data structured like this:

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? 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

解决方案

Using acast is one way to go. 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

这篇关于将数据框转换为矩阵:两列作为行名和列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆