rrefactoringpredefined-variables

Predefine the factors in table function in R


I would like to predefine the levels of the table function to make the results comparable among distinct datasets. Let's say that I would like to compare obj1 and obj2:

obj1 <-c(1,1,1,2,3)

obj2 <- c(1,1,1,2,2)

If I use table function on them the results have different factors:

> table(obj1)
obj1
1 2 3
3 1 1
> table(obj2)
obj2
1 2
3 2

I tried to predefine the levels without success:

table(obj2, deparse.level = 3)

Error in vapply(l[fixup], function(x) switch(deparse.level + 1, "", if (is.symbol(x)) as.character(x) else "", : values must be length 1, but FUN(X[[1]]) result is length 0

Any ideas?


Solution

  • Right now, you just have numbers. If you make the obj's factors, you can declare the factor levels.

    obj1 <- factor(c(1,1,1,2,3), levels=1:3)
    obj2 <- factor(c(1,1,1,2,2), levels=1:3)
    table(obj1)
    obj1
    1 2 3 
    3 1 1 
    table(obj2)
    obj2
    1 2 3 
    3 2 0