Krzysztof Krzysztof - 3 months ago 9
R Question

How to add columns to table using R

I have table A made using table()

Table A
0 1 2 4
2300 31 4 1


and

Table B
0 1 2 3
2123 31 4 1


I want to make plot from them but Table A is missing column with 3. I want to add column 3 to table A with 0 and column 4 to table B with 0.
Or maybe solution is with table, according to https://stat.ethz.ch/R-manual/R-devel/library/base/html/table.html table() builds contingency table of the counts at each combination of factor levels. So when I don't have 3 occurances in my data it not shows in Table A.

Answer

We can convert to factor with levels specified for the 'A' and 'B' vectors.

table(factor(A, levels = 0:4))
table(factor(B, levels = 0:4))

data

set.seed(24)
A <- sample(c(0, 1, 2, 4), 2500, replace = TRUE)
B <- sample(0:3, 2500, replace = TRUE)