简体   繁体   中英

How to force table to have equal dimensions?

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,3,3,3,3,5,5,6)
c <- table(a,b)

print(c)
#   b
#a   1 2 3 5 6
#  0 1 0 0 0 0
#  1 0 1 1 0 0
#  2 0 0 1 0 0
#  3 0 0 2 1 0
#  4 0 0 2 1 0
#  5 0 0 2 0 1

However, I am looking for the following result:

print(c)
#   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

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)

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