How to force table to have equal dimensions?

后端 未结 1 1305
夕颜
夕颜 2020-12-22 05:46

How can I force the dimensions of a table to be equal in R?

For example:

a <- c(0,1,2,3,4,5,1,3,4,5,3,4,5)
b <- c(1,2,3,3,3,3         


        
相关标签:
1条回答
  • 2020-12-22 06:19

    By using factors. table doesn't know the levels of your variable unless you tell it in some way!

    a <- c(0,1,2,3,4,5,1,3,4,5,3,4,5)
    b <- c(1,2,3,3,3,3,3,3,3,3,5,5,6)
    
    a <- factor(a, levels = 0:6)
    b <- factor(b, levels = 0:6)
    table(a,b)
    #   b
    #a   0 1 2 3 4 5 6
    #  0 0 1 0 0 0 0 0
    #  1 0 0 1 1 0 0 0
    #  2 0 0 0 1 0 0 0
    #  3 0 0 0 2 0 1 0
    #  4 0 0 0 2 0 1 0
    #  5 0 0 0 2 0 0 1
    #  6 0 0 0 0 0 0 0
    

    Edit The general way to force a square cross-tabulation is to do something like

    x <- factor(a, levels = union(a, b))
    y <- factor(b, levels = union(a, b))
    table(x, y)
    
    0 讨论(0)
提交回复
热议问题