# [R] table command

Marc Schwartz marc_schwartz at me.com
Sat Apr 24 16:20:42 CEST 2010

```On Apr 24, 2010, at 8:59 AM, Shubha Vishwanath Karanth wrote:

> Hi,
>
>
>
> Let s be a dataframe.
>
>
>
>> s
>
>   A B C
>
>   0 0 1
>
>   1 0 1
>
>   1 0 1
>
>   0 0 1
>
>   1 0 1
>
>   0 1 1
>
>   0 1 1
>
>   0 1 1
>
>   0 0 1
>
>
>
>> tab1=table(s[,c(1,2)])
>
>> tab1
>
>   B
>
> A   0 1
>
>  0 3 3
>
>  1 3 0
>
>
>
>> tab2=table(s[,c(1,3)])
>
>> tab2
>
>   C
>
> A   1
>
>  0 6
>
>  1 3
>
>
>
>
>
> The problem is I need to access frequency corresponding to (0,0).
> tab1[1] will give me the correct value while tab2[1] will not give the
> frequency which I expected. So, is there a possibility in the table
> command to have the order of tab1 and tab2 being equal? (here 2*2). May
> be by filling in the appropriate value as 0 or NA?
>
>
>
> Thanks,
>
> Shubha

In this case, 'C' has no 0's, so that value is not considered in the tabulation in the second table.

If you coerce each column to a factor with common levels, then you can obtain consistent formats for the output of table. Even though there are no 0's in 'C', that 'C' as a factor now has levels of 0 and 1, they will both be included in the table() output.

s.new <- data.frame(lapply(s, factor, levels = 0:1))

> str(s.new)
'data.frame':	9 obs. of  3 variables:
\$ A: Factor w/ 2 levels "0","1": 1 2 2 1 2 1 1 1 1
\$ B: Factor w/ 2 levels "0","1": 1 1 1 1 1 2 2 2 1
\$ C: Factor w/ 2 levels "0","1": 2 2 2 2 2 2 2 2 2

> s.new
A B C
1 0 0 1
2 1 0 1
3 1 0 1
4 0 0 1
5 1 0 1
6 0 1 1
7 0 1 1
8 0 1 1
9 0 0 1

> table(s.new[, c(1, 2)])
B
A   0 1
0 3 3
1 3 0

> table(s.new[, c(1, 3)])
C
A   0 1
0 0 6
1 0 3

See ?factor, ?lapply and ?data.frame

HTH,

Marc Schwartz

```