1

I have a dataframe variable myDF that looks like this:

A  B
0  1
0  1
0  1  
0  1

If I run xtabs(data=myDF) I get a 1 X 1 matrix that shows that factor B=1 exactly 4 times and A=0 exactly 4 times.

I would like to get a 2X2 matrix that also indicates that B=0 and A=0 exactly 0 times etc.

I have been looking at the docs and am not sure how this is done. How do I specify that I should include missing levels? I am comfortable with python but pretty new to R.

Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
Bernie2436
  • 153
  • 1
  • 6

2 Answers2

1

You need to convert A and B to the factor class and both of them have the same levels 0 and 1.

df[] <- lapply(myDF, factor, levels = c(0, 1))
table(df)

   B
A   0 1
  0 0 4
  1 0 0
Darren Tsai
  • 32,117
  • 5
  • 21
  • 51
0

We can also use stack

table(stack(myDF))
#    ind
#values A B
#    0 4 0
#    1 0 4

Or with dplyr

library(dplyr)
library(tidyr)
myDF %>% 
     mutate_all(factor, levels = 0:1) %>% 
     count(A, B, .drop = FALSE) %>%
     pivot_wider(names_from = B, values_from = n)

data

myDF <- structure(list(A = c(0L, 0L, 0L, 0L), B = c(1L, 1L, 1L, 1L)),
  class = "data.frame", row.names = c(NA, 
-4L))
akrun
  • 874,273
  • 37
  • 540
  • 662