Make all values > 0
from table
equal to "1" before using crossprod
:
(table(houses, animals) > 0) *1
# animals
# houses cat dog rat spider
# 1 1 1 0 0
# 2 1 0 0 0
# 3 0 1 0 0
# 4 1 0 1 1
# 5 1 0 1 0
# 6 1 0 0 0
out <- crossprod((table(houses, animals) > 0) *1)
out[lower.tri(out, diag=TRUE)] <- NA
as.table(out)
# animals
# animals cat dog rat spider
# cat 1 2 1
# dog 0 0
# rat 1
# spider
To get to the desired output, since we know that the first column and the last row will be empty, and since you already figured out on your own that as.table
would take care of not printing the NA
values, continuing from above, you can do:
out <- as.table(out[-nrow(out), -1])
out
# animals
# animals dog rat spider
# cat 1 2 1
# dog 0 0
# rat 1