Get a square matrix out of a non symetric data frame

后端 未结 1 1339
时光取名叫无心
时光取名叫无心 2021-01-21 11:17

I\'m a total beginner in R. I have a series of data relating the surnames of married persons.

    Id_mar  Wife  Husband
1      1    Smith Johnson
2      2    Sm         


        
1条回答
  •  说谎
    说谎 (楼主)
    2021-01-21 11:47

    Based on the expected output, we can use table (as @David Arenburg mentioned in the comments) on factor converted 'Wife' and 'Husband' columns, specifying the levels as the sorted unique elements of both the columns ('Un1')

     Un1 <- sort(unique(unlist(df1[-1])))
     table(factor(df1$Wife, levels=Un1), factor(df1$Husband, levels=Un1))
     #          Carter Johnson Smith Wang White
     # Carter       0       0     0    0     0
     # Johnson      0       0     0    0     0
     # Smith        1       1     0    0     0
     # Wang         0       0     1    0     0
     # White        2       0     0    0     0
    

    Or we can use mtabulate from qdapTools.

     library(qdapTools)
     mtabulate(as.data.frame(t(df1[-1])))
    

    0 讨论(0)
提交回复
热议问题