[R] Transform pairwise observations into a table

Rui Barradas ruipbarradas at sapo.pt
Mon Oct 1 19:05:53 CEST 2012


Hello,

Try the following.


dat <- read.table(text="
ind1 ind2 coef
1 1 1
1 2 0.25
1 3 0.125
1 4 0.5
2 2 1
2 1 0.25
2 3 0.125
2 4 0.5
3 3 1
3 1 0.125
3 2 0.125
3 4 0.5
4 4 1
4 1 0.5
4 2 0.5
4 3 0.5
", header=TRUE)
dat

reshape(dat, v.names = "coef", idvar = "ind1", timevar = "ind2",
         direction = "wide")

Hope this helps,

Rui Barradas
Em 01-10-2012 17:17, AHJ escreveu:
> Hi,
>
> I have a table of pairs of individuals and a coefficient that belongs to the
> pair:
>
> ind1	ind2	coef
> 1	1	1
> 1	2	0.25
> 1	3	0.125
> 1	4	0.5
> 2	2	1
> 2	1	0.25
> 2	3	0.125
> 2	4	0.5
> 3	3	1
> 3	1	0.125
> 3	2	0.125
> 3	4	0.5
> 4	4	1
> 4	1	0.5
> 4	2	0.5
> 4	3	0.5
>
> And I want to convert it to a matrix where each individual is both a row and
> a column and at the intersection of each pair is the coefficient that
> belongs to that pair:
>
> 	1	       2	       3	         4
> 1	1	       0.25	       0.125	0.5
> 2	0.25      1	       0.125	0.5
> 3	0.125    0.125    1	        0.5
> 4	0.5	       0.5	       0.5	        1
>
> If table() would allow me to specify something other than frequencies to
> fill the table with, it would be what I need. I tried a few different
> combinations of t() and unique() but none of it made enough sense to post as
> my starting code... I am just lost. Any help would be greatly appreciated.
>
> Thank you,
> AHJ
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Transform-pairwise-observations-into-a-table-tp4644706.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list