Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add a factor level to a table

I have built a contingency table from a column in a dataframe:

> dat <- data.frame(x = c(1, 1, 3))
> table(dat)
x
1 3 
2 1

I want to add a "column" to the table for the missing factor levels (in this case "2") with a count of 0. The result should look like this:

> table(dat)
x
1 2 3 
2 0 1

I have searched the site and found many similar questions, but while they use the term "table" in the question title and body, they all actually ask about dataframes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to explicitly specify the levels, i.e.

table(factor(dat$x, levels = 1:3))

# 1 2 3
# 2 0 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading