Converting from a Dataframe to a Table

The reverse procedure of creating a table from a dataframe is much more straightforward, and involves nothing more than the table function:

table(dbtable)

, , condition = healthy

    age
sex      old   young
 female    8       9
   male    7      12
, , condition = parasitized
    age
sex      old   young
 female    5       8
   male    7       6

You might want this tabulated object itself to be another dataframe, in which case use

as.data.frame(table(dbtable))

      sex     age    condition    Freq
1  female     old      healthy       8
2    male     old      healthy       7
3  female   young      healthy       9
4    male   young      healthy      12
5  female     old  parasitized       5
6    male     old  parasitized       7
7  female   young  parasitized       8
8    male   young  parasitized       6

You will see that R has invented the variable name Freq for the counts of the various contingencies. To change this to ‘count’ use names with the appropriate subscript [4]:

frame<-as.data.frame(table(dbtable))
names(frame)[4]<-"count"
frame

      sex    age   condition  count
1  female    old     healthy      8
2    male    old     healthy      7
3  female  young     healthy      9
4    male  young     healthy     12
5  female    old parasitized      5
6    male    old parasitized      7
7  female  young parasitized      8
8    male  young parasitized      6

Get The R Book now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.