0

I am a bit confused on how to use dcast function even after reading the documentation. I am trying to dcast a molten dataframe as below

> head(res)
       factoroneid      factortwoid           val
1                1                1  5.8223670800
2                1                2 -1.3314644000
3                1                3  0.7206910120
4                1                4  0.0762039224
5                1                5  2.7409736300
6                1                6  0.0896606575

res contains 1st column and 2nd column as indices. I need to use 1st column data as row number and 2nd column data as column number and generate a matrix with value from 3rd column. I am trying something like this but the data doesn't look correct.

temp <- dcast(res, factoroneid + factortwoid ~ val)

expected output should be:

   1         2     3      4  ... 
1  5.82  -1.33  0.72  0.076  ...
2
3
4
.
.

Could you please suggest?

Alok
  • 3,160
  • 3
  • 28
  • 47

1 Answers1

1
dcast(res, factoroneid ~ factortwoid)

Works for me.

BrodieG
  • 51,669
  • 9
  • 93
  • 146
  • Thanks. That seems simple :). I wasn't sure how to specify val in output result. To understand better, in this case since its only a single column it just copies the value but if there were multiple columns then we would need a bay to aggregate them using aggregate function (for eg SUM). Is my understanding correct? – Alok Jan 24 '14 at 07:28
  • 1
    @Alok, Not entirely. You need the aggregation function if there are multiple values from the same column that match any single `factoroneid ~ factorwoid` combination. If you have multiple value columns that you want in your casted data frame, you first need to `melt` your data further so that you have only one value column, and only then `dcast`. See [explanation by Andrie](http://stackoverflow.com/questions/11608167/cast-multiple-value-columns). If you have multiple value columns but only want to preserve one, then you use `value.var`. – BrodieG Jan 24 '14 at 12:52