The %<>%
operator from {magrittr} may be unfamiliar. It just sends an object to a function and overwrites it back.
suppressPackageStartupMessages({
library(dplyr)
library(Matching)
library(magrittr)
library(tableone)
})
cohort <- data.frame(
outcome = c(0, 0, 0, 1, 0),
exposure = c(0, 0, 0, 1, 1),
insurance = c(1, 1, 1, 1, 1),
language = c(3, 1, 1, 1, 1),
age = c(32, 36, 22, 26, 38),
bmi = c(23.8407, 25.354099, 29.709999, 26.9098, 36.290401),
race_eth = as.factor(c("5", "1", "2", "1", "2")),
nullip = as.factor(c("1", "0", "1", "1", "0"))
)
cohort %<>% mutate(across(where(is.factor), as.numeric))
xvars <- c("race_eth", "insurance", "language", "nullip", "age", "bmi")
table1 <- CreateTableOne(vars=xvars, strata="exposure",data=cohort, test=FALSE)
print(table1, smd=TRUE)
#> Stratified by exposure
#> 0 1 SMD
#> n 3 2
#> race_eth (mean (SD)) 2.00 (1.00) 1.50 (0.71) 0.577
#> insurance (mean (SD)) 1.00 (0.00) 1.00 (0.00) <0.001
#> language (mean (SD)) 1.67 (1.15) 1.00 (0.00) 0.816
#> nullip (mean (SD)) 1.67 (0.58) 1.50 (0.71) 0.258
#> age (mean (SD)) 30.00 (7.21) 32.00 (8.49) 0.254
#> bmi (mean (SD)) 26.30 (3.05) 31.60 (6.63) 1.027
greedymatch <- Match(Tr=cohort$exposure, M=1, X=cohort[xvars])
matched <- cohort[unlist(greedymatch[c("index.treated", "index.control")]),]
matched
#> outcome exposure insurance language age bmi race_eth nullip
#> 4 1 1 1 1 26 26.9098 1 2
#> 5 0 1 1 1 38 36.2904 2 1
#> 3 0 0 1 1 22 29.7100 2 2
#> 2 0 0 1 1 36 25.3541 1 1