Chapter 5 General Codes

5.1 with and table

The data always have 0 and 1 indicating exposure/disease/confounder status, to get contigency tables for further calculation, we use with and table.

dat <- foreign::read.dta("./_data/diet.dta")
head(dat)
##   act diet mort
## 1   0    0    1
## 2   0    0    0
## 3   0    0    1
## 4   0    0    1
## 5   0    0    0
## 6   0    0    0

5.1.1 2 way table

  • table uses the cross-classifying factors to build a contingency table of the counts at each combination of factor levels.

    • The input data for table should be one or more objects which can be interpreted as factors.

    • To create a two by two table for exposure and disease: table(data$exposure, data$disease)

table(dat$diet, dat$mort)
##    
##       0   1
##   0 186 136
##   1 119  59
  • with(data, expr, ...): evaluate an R expression in an environment constructed from data

    • data: data to use for constructing an environment.
    • expr: expression to evaluate, in this case we use table()
with(dat, table(diet,mort))
##     mort
## diet   0   1
##    0 186 136
##    1 119  59
  • The same results as using table() function only

    • As the environment has been constructed, there‚Äôs no need to use dat$ to tell R how to find the factor.

5.1.2 3 way table

  • Similar method as 2 way table, but indicate the third factor using by =

    • To create a three way table for exposure and disease: with(data, table(exposure, disease, by = confounder))
table3 <- with(dat, table(diet, mort, by = act))
table3
## , , by = 0
## 
##     mort
## diet  0  1
##    0 75 75
##    1 22 17
## 
## , , by = 1
## 
##     mort
## diet  0  1
##    0 45 40
##    1 36 28
## 
## , , by = 2
## 
##     mort
## diet  0  1
##    0 34 14
##    1 37 10
## 
## , , by = 3
## 
##     mort
## diet  0  1
##    0 32  7
##    1 24  4