ROY ROY - 2 months ago 11
R Question

Create a count table with unequal number to variables

I have the following dataset

zx
:

#zx

A B C D
1 COW COW BIRD COW
2 COW BIRD COW COW
3 FLOWER DND BIRD DND
4 COW COW BIRD FLOWER
5 FLOWER FLOWER DND COW
6 FLOWER COW COW BIRD


I want to create a count table which should look like this:

A B C D
COW 3 3 2 3
BIRD 0 1 3 1
FLOWER 3 1 0 1
DND 0 1 1 1


I have tried using following code but it shows an error as there is no
DND
and
BIRD
in first column, i.e. there is an unequal number of variables among columns:

countsd <- data.frame(apply(zx, 2, count))

Answer

You can use apply column wise.

Basically, creating every element into a factor with all the unique values present in the dataframe as levels and then calculating the frequency of that level in the column.

apply(zx, 2, function(x) table(factor(x, levels = unique(unlist(zx)))))

#       A B C D
#COW    3 3 2 3
#FLOWER 3 1 0 1
#BIRD   0 1 3 1
#DND    0 1 1 1