Skip to contents

Create a two way data table

Usage

tbl_2var(
  data,
  formula,
  row_pct = c("hide", "show"),
  digits = 3,
  caption = NULL,
  na_rm = TRUE
)

Arguments

data

A data frame.

formula

The variables to tabulate. Should be given in formula notation var1~var2. Changing the order of the variables will swap the table axes.

row_pct

Should row percents be included in each cell? Defaults to "hide" with the only other possible value being "show".

digits

The number of digits to round to. Defaults to 3.

caption

An optional caption for the table. Defaults to NULL, but a sensible default is provided within the function.

na_rm

Should missing values be removed? Defaults to TRUE.

Value

An object of class flextable. If in an interactive session, the table will be viewable immediately.

Examples

tbl_2var(mtcars, cyl~gear)
Two-Way Counts of cyl vs. gear
cyl Missing: 0 | gear Missing: 0
NAs Removed: Yes

cyl

gear

4

6

8

Total

3

1

2

12

15

4

8

4

0

12

5

2

1

2

5

Total

11

7

14

32

tbl_2var(mtcars, cyl~gear, row_pct = "show")
Two-Way Counts (with Row Percentages) of cyl vs. gear
cyl Missing: 0 | gear Missing: 0
NAs Removed: Yes

cyl

gear

4

6

8

Total

3

1
(6.67%)

2
(13.33%)

12
(80.00%)

15
(100.00%)

4

8
(66.67%)

4
(33.33%)

0
(0.00%)

12
(100.00%)

5

2
(40.00%)

1
(20.00%)

2
(40.00%)

5
(100.00%)

Total

11
(34.38%)

7
(21.88%)

14
(43.75%)

32
(100.00%)

tbl_2var(mtcars, cyl~gear, caption = "This is the new caption")
This is the new caption
cyl Missing: 0 | gear Missing: 0
NAs Removed: Yes

cyl

gear

4

6

8

Total

3

1

2

12

15

4

8

4

0

12

5

2

1

2

5

Total

11

7

14

32

# Will give an error try(tbl_2var(mtcars, Cyl~Gear)) #> Error in value[[3L]](cond) : #> Could not complete the process. Perhaps you spelled the dataset name or #> a variable name wrong? Hint: R is case-sensitive.