Ogustari Ogustari - 1 year ago 67
R Question

Make a matrix from a data frame containing numeric and character value

I have a data frame containing three columns like this:

IS1 IS2 Dist
A A 0
A B 1
A C 2
A D 3
B B 0
B C 4
B D 5
C C 0
C D 6
D D 0


I would like to obtain a matrix like this:

A B C D
A 0 1 2 3
B 1 0 4 5
C 2 4 0 6
D 3 5 6 0


Any suggestion?

Answer Source

We can do this with xtabs

r1 <- xtabs( Dist ~IS2 + IS1, df1)
r1+ t(r1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download