in R: Two Way Match to Matrix

前端 未结 2 344
日久生厌
日久生厌 2021-01-24 22:42

If I have a data.frame

df <- data.frame(DEP=letters[1:5], ARR=letters[11:15], NO=1:5+5)

   DEP ARR  NO
1   a   k   6
2   b   l   7
3   c   m   8
4   d   n            


        
相关标签:
2条回答
  • 2021-01-24 22:55

    If I understood your question correctly, you could use a sparse matrix definition:

    library(Matrix)
    mat <- spMatrix(length(df$DEP), length(df$ARR), 
                    seq(df$DEP), seq(df$ARR), as.numeric(as.character(df$NO)))
    rownames(mat) <- df$DEP
    colnames(mat) <- df$ARR
    #> as.matrix(mat)
    #  k l m n  o
    #a 6 0 0 0  0
    #b 0 7 0 0  0
    #c 0 0 8 0  0
    #d 0 0 0 9  0
    #e 0 0 0 0 10
    
    0 讨论(0)
  • 2021-01-24 23:03

    ?xtabs:

    xtabs(NO ~ ., data=df)
    #   ARR
    #DEP  k  l  m  n  o
    #  a  6  0  0  0  0
    #  b  0  7  0  0  0
    #  c  0  0  8  0  0
    #  d  0  0  0  9  0
    #  e  0  0  0  0 10
    
    0 讨论(0)
提交回复
热议问题