twowo
twowo

Reputation: 631

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

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

Upvotes: 1

Views: 4489

Answers (2)

James
James

Reputation: 66834

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

Upvotes: 7

Luciano Selzer
Luciano Selzer

Reputation: 10016

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

Upvotes: 7

Related Questions