table()
is one option:
db <- read.table(text = "ID Group Drink
1 A yes
2 A no
3 A NA
4 B no
5 B no
6 B yes", header = TRUE)
with(db, table(Drink))
with(db, table(Group, Drink))
> with(db, table(Drink))
Drink
no yes
3 2
> with(db, table(Group, Drink))
Drink
Group no yes
A 1 1
B 2 1
Including the NA
as a class is achieved by the useNA
argument:
with(db, table(Drink, useNA = "ifany"))
> with(db, table(Drink, useNA = "ifany"))
Drink
no yes <NA>
3 2 1
You can of course store the objects returned by table()
and access them as any other matrix/array:
tab <- with(db, table(Drink, useNA = "ifany"))
tab[1]
tab2 <- with(db, table(Group, Drink, useNA = "ifany"))
tab2[,1]
tab2[1,]
> tab <- with(db, table(Drink, useNA = "ifany"))
> tab[1]
no
3
> tab <- with(db, table(Drink, useNA = "ifany"))
> tab[1]
no
3
> tab2 <- with(db, table(Group, Drink, useNA = "ifany"))
> tab2[,1]
A B
1 2
> tab2[1,]
no yes <NA>
1 1 1