rsquaredacademy / descriptr
1 1
cross_table2 <- function(var1, var2, name_1, name_2) UseMethod("cross_table2")
2

3
cross_table2.default <- function(var1, var2, name_1, name_2) {
4

5 1
  var_1       <- deparse(substitute(var1))
6 1
  var_2       <- deparse(substitute(var2))
7 1
  var_na      <- c(var_1, var_2)
8 1
  var_names   <- c(name_1, name_2)
9 1
  x           <- as.matrix(table(var1, var2))
10 1
  n           <- sum(x)
11 1
  row_name    <- levels(var1)
12 1
  per_mat     <- round(x / n, 3)
13 1
  per_mat_row <- apply(per_mat, 1, sum)
14 1
  per_mat_col <- apply(per_mat, 2, sum)
15 1
  per_mat     <- cbind(per_mat, per_mat_row)
16 1
  per_mat     <- suppressWarnings(rbind(per_mat, per_mat_col))
17 1
  rowtotal    <- apply(x, 1, sum)
18 1
  coltotal    <- apply(x, 2, sum)
19 1
  rcent       <- row_pct(x, rowtotal)
20 1
  rcent       <- cbind(rcent, per_mat_row)
21 1
  rcent       <- apply(rcent, c(1, 2), rounda)
22 1
  ccent       <- col_pct(x, coltotal)
23 1
  ccent       <- apply(ccent, c(1, 2), rounda)
24 1
  x           <- cbind(x, rowtotal)
25 1
  x           <- cbind(row_name, x)
26 1
  col_name    <- levels(var2)
27 1
  col_names   <- c(var_names[1], col_name, "Row Total")
28 1
  last_line   <- c("Column Total", coltotal, n)
29

30 1
  result <- list(obs             = n,
31 1
                 variable_levels = col_name,
32 1
                 row_name        = row_name,
33 1
                 variable_names  = var_names,
34 1
                 column_names    = col_names,
35 1
                 twowaytable     = x,
36 1
                 percent_table   = per_mat,
37 1
                 row_percent     = rcent,
38 1
                 column_percent  = ccent,
39 1
                 column_totals   = last_line,
40 1
                 percent_column  = per_mat_col
41
  )
42

43

44 1
  class(result) <- "cross_table2"
45 1
  return(result)
46
}
47

48

49
print.cross_table2 <- function(x, ...) {
50 1
  print_cross2(x)
51
}

Read our documentation on viewing source code .

Loading