简体   繁体   中英

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?

We can do this with xtabs

r1 <- xtabs( Dist ~IS2 + IS1, df1)
r1+ t(r1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM