Home > Net >  How to get a contingency table with paddling in R
How to get a contingency table with paddling in R

Time:10-12

I want to tabulate a contingency table, for example

a = c(1, 3, 4)
b = c(2, 3, 5)
a_b = data.frame(a, b)
table(a_b)

And I got

   b
a   2 3 5
  1 1 0 0
  3 0 1 0
  4 0 0 1

But what I want is

   b
a   1 2 3 4 5
  1 0 1 0 0 0
  2 0 0 0 0 0
  3 0 0 1 0 0
  4 0 0 0 0 1
  5 0 0 0 0 0

How can I get this table?

Thank you

CodePudding user response:

We can create factor with levels specified as the unique elements from both the columns

lvls <- sort(unique(unlist(a_b)))
table(lapply(a_b, factor, levels = lvls))

-output

  b
a   1 2 3 4 5
  1 0 1 0 0 0
  2 0 0 0 0 0
  3 0 0 1 0 0
  4 0 0 0 0 1
  5 0 0 0 0 0

CodePudding user response:

Another approach could be to consider your data as a sparse matrix and create the matrix like this

a = c(1, 3, 4)
b = c(2, 3, 5)

library(Matrix)
m <- sparseMatrix(a, b, dims = c(5, 5))

 matrix(m, nrow = 5, ncol = 5)

#      [,1] [,2] [,3] [,4] [,5]
# [1,]    0    1    0    0    0
# [2,]    0    0    0    0    0
# [3,]    0    0    1    0    0
# [4,]    0    0    0    0    1
# [5,]    0    0    0    0    0
  • Related