In R, how can I check if two factors are equivalent?

I am generating a large list of factors with different levels, and I want to be able to detect when two of them define the same section. For example, I want to detect all of the following as equivalent to each other:

x1 <- factor(c("a", "a", "b", "b", "c", "c", "a", "a")) x2 <- factor(c("c", "c", "b", "b", "a", "a", "c", "c")) x3 <- factor(c("x", "x", "y", "y", "z", "z", "x", "x")) x4 <- factor(c("a", "a", "b", "b", "c", "c", "a", "a"), levels=c("b", "c", "a")) 

What is the best way to do this?

+4
source share
1 answer

I think you want to establish that two-way tabs have the same number of filled levels as a one-way classification. The default value in interaction should represent all levels, even if they are not filled, and the drop = TRUE parameter changes it according to your purpose:

 > levels (interaction(x1,x2, drop=TRUE) ) [1] "ca" "bb" "ac" > length(levels(x1) ) == length(levels(interaction(x1,x2,drop=TRUE) ) ) [1] TRUE 

The generalization will look at all( <the 3 necessary logical comparisons> ) :

  all( length(levels(x1) ) == length(levels(interaction(x1,x2,drop=TRUE) ) ), length(levels(x1) ) == length(levels(interaction(x1,x3,drop=TRUE) ) ), length(levels(x1) ) == length(levels(interaction(x1,x4,drop=TRUE) ) ) ) #[1] TRUE 
+4
source

Source: https://habr.com/ru/post/1436906/


All Articles